getApplicationContext() Issue - java

I'm following this tutorial :
http://www.tutos-android.com/importer-ajouter-certificat-ssl-auto-signe-bouncy-castle-android/comment-page-2#comment-2159
(SSl auto signed certificate problem)
JsonParserFUnction code :
package com.example.androidsupervision;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.security.KeyManagementException;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.UnrecoverableKeyException;
import java.security.cert.CertificateException;
import java.util.ArrayList;
import java.util.List;
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.scheme.SchemeRegistry;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.conn.ssl.X509HostnameVerifier;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.conn.SingleClientConnManager;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.content.Context;
import android.util.Log;
public class JsonReaderPost {
public JsonReaderPost() {
}
public void Reader() throws IOException, JSONException, KeyStoreException, NoSuchAlgorithmException, CertificateException, KeyManagementException, UnrecoverableKeyException {
String ints = "";
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("query","SELECT+AlertId+FROM+Orion.Alerts"));
//HttpClient client = new DefaultHttpClient();
**//Here is the problem**
HttpClient client =new MyHttpClient(getApplicationContext());
HttpPost httpPost = new
HttpPost("https://192.168.56.101:17778/SolarWinds/InformationService/v3/Json/Query");
httpPost.addHeader("content-type", "application/json");
httpPost.addHeader("Authorization", "Basic YWRtaW46");
httpPost.setEntity(new UrlEncodedFormEntity(params));
HttpResponse response;
String result = null;
response = client.execute(httpPost);
HttpEntity entity = response.getEntity();
if (entity != null) {
// A Simple JSON Response Read
InputStream instream = entity.getContent();
result = convertStreamToString(instream);
// now you have the string representation of the HTML request
// System.out.println("RESPONSE: " + result);
Log.e("Result", "RESPONSE: " + result);
instream.close();
}
// Converting the String result into JSONObject jsonObj and then into
// JSONArray to get data
JSONObject jsonObj = new JSONObject(result);
JSONArray results = jsonObj.getJSONArray("results");
for (int i = 0; i < results.length(); i++) {
JSONObject r = results.getJSONObject(i);
ints = r.getString("AlertId");
Log.e("Final Result", "RESPONSE: " + ints);
}
}
public static String convertStreamToString(InputStream is) {
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line = null;
try {
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return sb.toString();
}
}
I get in this line an error :
HttpClient client =new MyHttpClient(getApplicationContext());
The error is : The method getApplicationContext() is undefined for the type JsonReaderPost

You should send the context of your activity when you instantiate the class:
private Context mContext;
public JsonReaderPost(Context mContext) {
this.mContext = mContext;
}
Then, you should use "mContext" instead of getApplicationContext();

It is unknown because your class doesn't extend any other Class that has a Context, so it doesn't know what that method is. Such is, for example, an Activity.
However, using getApplicationContext(), unless you really know what you're doing, is almost always wrong. This will bring undesired behaviors like Exceptions when handled not properly. You should always use the Context of the class you're handling.
You can know which classes implement Context and get more info on contexts here.

Related

How to send https post request to with parameter to an api

I'm trying to send https post request to my api that send json response, this is a search function so it will require 1 parameter, but i cannot get the expected result from my api, here are my code
Handler.java
import android.util.Log;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.scheme.SchemeRegistry;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.conn.SingleClientConnManager;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpParams;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.net.URL;
import java.util.List;
import javax.net.ssl.HttpsURLConnection;
public class Handler {
static InputStream is = null;
static String response = null;
public final static int GET = 1;
public final static int POST = 2;
public Handler(){
}
public String makeServiceCall(String url, int method) {
return this.makeServiceCall(url, method, null);
}
public String makeServiceCall(String url, int method, List<NameValuePair> params){
try {
SchemeRegistry schemeRegistry = new SchemeRegistry();
schemeRegistry.register(new Scheme("https", SSLSocketFactory.getSocketFactory(), 443));
HttpParams params2 = new BasicHttpParams();
SingleClientConnManager mgr = new SingleClientConnManager(params2, schemeRegistry);
DefaultHttpClient httpClient = new DefaultHttpClient(mgr, params2);
HttpEntity httpEntity = null;
HttpResponse httpResponse = null;
if(method == POST){
HttpPost httpPost = new HttpPost(url);
if(params != null){
httpPost.setEntity(new UrlEncodedFormEntity(params));
}
httpResponse = httpClient.execute(httpPost);
} else if (method == GET) {
HttpGet httpGet = new HttpGet(url);
httpResponse = httpClient.execute(httpGet);
}
httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e){
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(is, "UTF-8"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while((line = reader.readLine()) != null){
sb.append(line + "\n");
}
is.close();
response = sb.toString();
} catch (Exception e){
Log.e("Buffer Error", "Error : " + e.toString());
}
return response;
}
makeServiceCall is used to make the request to url, but it only works with GET request and couldnt work with POST request, how do i fix this?

Java Refreshing Auth token after 30 min

I want to know how to keep refreshing token every 30 min. Currently i dont have it. I need to cache that token for 30 min and then replace current token with the new refresh token.
Right now when i pass 1000 records all records uses same Auth token but the program runs more than 1 hour. I get Auth token expired error for some of the records.
Can anyone help me with how to handle that scenario ?
Thanks in advance
This is call class and will be calling token class.
package main.java.com.test;
import java.io.IOException;
import java.io.PrintStream;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.util.concurrent.TimeUnit;
import org.apache.pig.EvalFunc;
import org.apache.pig.data.Tuple;
import com.google.common.base.Stopwatch;
public class Call {
private final String USER_AGENT = "Mozilla/5.0";
public static void main(String[] args) throws IOException
{
new Call().execute();
}
public String execute() throws IOException {
String number = "01";
String id = "0123456789";
String cd = "107BC0000X";
Token getToken = new Token();
String token = null;
try {
token = getToken.Token();
} catch (Exception e1) {
e1.printStackTrace();
}
System.out.println("access token" + token);
return token;
}
}
This is another class called Token
package main.java.com.test;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ClientConnectionManager;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.scheme.SchemeRegistry;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.codehaus.jettison.json.JSONObject;
public class Token {
private final String USER_AGENT = "Mozilla/5.0";
public String Token() throws Exception
{
Token http = new Token();
http.sendGet();
String token = http.sendPost();
return token;
}
private String sendPost() throws Exception
{
String url = "https://YOUR_AUTH0_DOMAIN/oauth/token";
HttpClient client = new DefaultHttpClient();
HttpClient httpClient1 = wrapClient(client);
HttpPost post = new HttpPost(url);
post.setHeader("User-Agent" , "Mozilla/5.0");
List urlParam = (List) new ArrayList();
urlParam.add(new BasicNameValuePair("client_id", ""));
urlParam.add(new BasicNameValuePair("grant_type", ""));
urlParam.add(new BasicNameValuePair("client_secret", ""));
post.setEntity(new UrlEncodedFormEntity(urlParam));
HttpResponse response = httpClient1.execute(post);
BufferedReader rd = new BufferedReader(new
InputStreamReader(response.getEntity().getContent()));
StringBuffer result = new StringBuffer();
String line = "";
while ((line = rd.readLine()) != null){
result.append(line);
}
String[] JsonTags0 = result.toString().split(",");
String[] JsonTags1 = result.toString().split(":");
String token1 = JsonTags1[1].trim();
return token1.substring(1,37);
}
private void sendGet()
{
}
public static HttpClient wrapClient(HttpClient base)
{
try {
SSLContext ctx = SSLContext.getInstance("TLS");
X509TrustManager tm = new X509TrustManager1();
ctx.init(null, new TrustManager[] {tm},null);
SSLSocketFactory ssf = new SSLSocketFactory(ctx);
ClientConnectionManager ccm = base.getConnectionManager(ctx , SSLSocketFactory , ALLOW_ALL_HOSTNAME_VERIFIER);
SchemeRegistry sr = ccm.getSchemeRegistry();
sr.register(new Scheme("https", ssf , 443));
return new DefaultHttpClient(ccm, base.getParams());
}
catch (Exception ex){
ex.printStackTrace();
return null;
}
}
}

ClassNotFoundException on org.apache.http.ssl.TrustStrategy

I'm trying to run a plugin that makes HTTP/HTTPS POST requests. On it its declared the needed dependencies, that is httpclient and httpcore. I'm using versions 4.5.3 and 4.4.6 respectively. Although imported correctly all (I mean), I got this error on execution time:
Caused by: java.lang.NoClassDefFoundError:
org/apache/http/ssl/TrustStrategy
25.06 19:59:12 [Server] INFO at
com.b5team.postrequest.Main.onCommand(Main.java:77) ~[?:?]
25.06 19:59:12 [Server] INFO at
org.bukkit.command.PluginCommand.execute(PluginCommand.java:44) ~
[Spigot.jar:git-Spigot-3fb9445-6e3cec8]
25.06 19:59:12 [Server] INFO ... 10 more
25.06 19:59:12 [Server] INFO Caused by:
java.lang.ClassNotFoundException: org.apache.http.ssl.TrustStrategy
And here is my code:
package com.b5team.postrequest;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.security.KeyManagementException;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.List;
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.SSLContext;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.config.Registry;
import org.apache.http.config.RegistryBuilder;
import org.apache.http.conn.socket.ConnectionSocketFactory;
import org.apache.http.conn.socket.PlainConnectionSocketFactory;
import org.apache.http.conn.ssl.NoopHostnameVerifier;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.ssl.SSLContextBuilder;
import org.apache.http.conn.ssl.TrustStrategy;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.message.BasicNameValuePair;
public class SocketPOSTRequest {
public void sendRequest(String myurl, String hash, String args[]) throws KeyManagementException, NoSuchAlgorithmException, KeyStoreException, ClientProtocolException, IOException {
HttpClientBuilder b = HttpClientBuilder.create();
SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null, new TrustStrategy() {
public boolean isTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {
return true;
}
}).build();
b.setSSLContext(sslContext);
HostnameVerifier hostnameVerifier = NoopHostnameVerifier.INSTANCE;
SSLConnectionSocketFactory sslSocketFactory = new SSLConnectionSocketFactory(sslContext, hostnameVerifier);
Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory> create()
.register("http", PlainConnectionSocketFactory.getSocketFactory())
.register("https", sslSocketFactory)
.build();
PoolingHttpClientConnectionManager connMgr = new PoolingHttpClientConnectionManager(socketFactoryRegistry);
b.setConnectionManager(connMgr);
HttpClient client = b.build();
HttpPost post = new HttpPost(myurl);
List<NameValuePair> params = new ArrayList<NameValuePair>(args.length);
params.add(new BasicNameValuePair("hash", hash));
for(int i = 0; i < args.length; i++) {
params.add(new BasicNameValuePair("arg"+i, args[i]));
}
post.setEntity(new UrlEncodedFormEntity(params, "UTF-8"));
HttpResponse response = client.execute(post);
HttpEntity entity = response.getEntity();
if (entity != null) {
InputStream in = entity.getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
String line;
System.out.println("[POSTRequest] Data sent successfully!");
while ((line = reader.readLine()) != null) {
System.out.println("[POSTRequest] Report: "+line);
}
}
}
}
EDIT: I'm using Ant to build, and the dependencies are correctly added. I tested too with Maven, adding the dependencies, but the error remains.
EDIT2: Switched to Maven, added maven-shade-plugin and maven-compile-plugin. The error disappeared, but now got this java.lang.NoSuchMethodError: org.apache.http.impl.client.HttpClientBuilder.setSSLContext. When running with junit, don't occurs any errors. It only occurs when running on server, that is Spigot 1.11.2 Minecraft Server.
if you are using a maven project, add the below dependency in your pom.xml file.
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.3</version>
</dependency>
So, I replaced the sslcontext methods from apache httpclient and httpcore with javax sslcontext methods. Now, everything works fine. Remembering, that the above code was working normally on pure java. The real problem was when running on Minecraft server.
Anyway, i will put below the new code, for documentation, maybe helps someone.
package com.b5team.postrequest;
import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;
import java.net.URL;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.KeyManager;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
public class HttpsPOSTRequest {
public static void sendRequest(String myurl, String hash, String args[]) throws NoSuchAlgorithmException, KeyManagementException {
try {
SSLContext context = SSLContext.getInstance("TLS");
context.init(new KeyManager[0], new TrustManager[] {new DefaultTrustManager()}, new SecureRandom());
SSLContext.setDefault(context);
URL url = new URL(myurl);
HttpsURLConnection con = (HttpsURLConnection)url.openConnection();
con.setHostnameVerifier(new HostnameVerifier() {
#Override
public boolean verify(String arg0, SSLSession arg1) {
return true;
}
});
con.setRequestMethod("POST");
con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
con.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0;Windows98;DigExt)");
con.setDoOutput(true);
con.setDoInput(true);
ArrayList<String> params = new ArrayList<String>(args.length + 1);
DataOutputStream output = new DataOutputStream(con.getOutputStream());
output.writeBytes("hash=" + hash);
for(int i = 0; i < params.size(); i++) {
output.writeBytes("&");
output.writeBytes("arg" + i + "=" + args[i]);
output.flush();
}
output.flush();
output.close();
DataInputStream input = new DataInputStream(con.getInputStream());
BufferedReader reader = new BufferedReader(new InputStreamReader(input));
String line;
System.out.println("[POSTRequest] Data sent successfully!");
System.out.println("[POSTRequest] Resp Code:"+con.getResponseCode());
System.out.println("[POSTRequest] Resp Message:"+con.getResponseMessage());
while ((line = reader.readLine()) != null) {
System.out.println("[POSTRequest] Report: "+line);
}
input.close();
} catch (UnsupportedEncodingException e) {
System.out.println("[POSTRequest] Encoding error. Maybe string have invalid caracters.");
e.printStackTrace();
} catch (MalformedURLException e) {
System.out.println("[POSTRequest] Invalid URL. Verify your URL and try again.");
e.printStackTrace();
} catch (IOException e) {
System.out.println("[POSTRequest] Error on HTTPS connection.");
e.printStackTrace();
}
}
private static class DefaultTrustManager implements X509TrustManager {
#Override
public void checkClientTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {}
#Override
public void checkServerTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {}
#Override
public X509Certificate[] getAcceptedIssuers() {
return null;
}
}
}

Error: "The Method is undefined for the type object" android project eclipse

I'm new android development and I have been researching this for some time however I can't seem to correct the error. I have a "The Method is undefined for the type object" error on both getStatusCode() and getReasonPhrase(). Any help would be appreciated.
My code as fallows
package com.javapapers.java.io;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpRequestBase;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.BasicHttpParams;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
public class HttpUtil {
public String getHttpResponse(HttpRequestBase request) {
String result = null;
try {
DefaultHttpClient httpClient = new DefaultHttpClient(new BasicHttpParams());
HttpResponse httpResponse = httpClient.execute(request);
int statusCode = httpResponse.getStatusLine().getStatusCode();
String reason = httpResponse.getStatusLine().getReasonPhrase();
StringBuilder sb = new StringBuilder();
if (statusCode == 200) {
HttpEntity entity = httpResponse.getEntity();
InputStream inputStream = entity.getContent();
BufferedReader bReader = new BufferedReader(
new InputStreamReader(inputStream, "UTF-8"), 8);
String line = null;
while ((line = bReader.readLine()) != null) {
sb.append(line);
}
} else {
sb.append(reason);
}
result = sb.toString();
} catch (UnsupportedEncodingException ex) {
} catch (ClientProtocolException ex1) {
} catch (IOException ex2) {
}
return result;
}
}

Invoke a method of a web service from a Java (Android) external app

sorry if the question is too easy, but I do not know the answer..
What I have to do is to invoke a method of a web service using a java app.
Here you can find a web service:
http://muovi.roma.it/ws/xml/autenticazione/1
And I want Invoke the method called "autenticazione.Accedi:"
I have a python example that is doing this:
from xmlrpclib import Server
from pprint import pprint
DEV_KEY = 'Inserisci qui la tua chiave'
s1 = Server('http://muovi.roma.it/ws/xml/autenticazione/1')
s2 = Server('http://muovi.roma.it/ws/xml/paline/7')
token = s1.autenticazione.Accedi(DEV_KEY, '')
res = s2.paline.Previsioni(token, '70101', 'it')
pprint(res)
But I need the same operation in Java... Can anyone help me in this problem?
thank you
I recommend you using this project as a Library.
https://github.com/matessoftwaresolutions/AndroidHttpRestService
It makes you easy deal with apis, control network problems etc.
You can find a sample of use there.
You only have to:
Build your URL
Tell the component to execute in POST/GET etc. mode
Build your JSON
I hope it helps!!!
package com.example.jojo.gridview;
import android.util.Log;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
/**
* Created by jojo on 12/10/15.
*/
public class WebService {
String url="http://192.168.1.15/Travel_Dairy/";
String invokeGetWebservice(String webUrl)
{
String result = "";
webUrl=webUrl.replace(" ","%20");
HttpClient httpclient = new DefaultHttpClient();
HttpGet httpget = new HttpGet(webUrl);
HttpResponse response;
try {
response = httpclient.execute(httpget);
HttpEntity entity = response.getEntity();
if (entity != null) {
InputStream inputstream= entity.getContent();
BufferedReader bufferedreader = new BufferedReader(
new InputStreamReader(inputstream), 2 * 1024);
StringBuilder stringbuilder = new StringBuilder();
String currentline = null;
try {
while ((currentline = bufferedreader.readLine()) != null) {
stringbuilder.append(currentline + "\n");
}
} catch (IOException e) {
e.printStackTrace();
}
result = stringbuilder.toString();
Log.e("Result", result);
inputstream.close();
return result;
}
} catch (ClientProtocolException e1) {
Log.e("ClientProtocolException", e1.toString());
return result;
} catch (IOException e1) {
Log.e("IOException", e1.toString());
return result;
}
return result;
}
public List<DataModel> getTrips() {
String getname="view_details.php?";
String completeurlforget=url+getname;
//String seturl= "ur_id="+userid;
//String finalurl=completeurlforget+seturl;
String result=invokeGetWebservice(completeurlforget);
try {
JSONArray jsonarry=new JSONArray(result);
List<DataModel> ar=new ArrayList();
for(int i=0;i<jsonarry.length();i++)
{
JSONObject jsonobj=jsonarry.getJSONObject(i);
DataModel user=new DataModel();
user.setName(jsonobj.getString("name"));
user.setImage(jsonobj.getString("image"));
ar.add(user);
}
return ar;
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
}

Categories

Resources