Using Intent to pass variable from Activity - java

I want to send a value("sessionId") from one activity to another. I have used intent for that but I don't know how to access that variable so that I can use it in Intent.
This is my java file:-
public class Login extends Activity {
//URL to get JSON Array
private static String url = "http://*************/webservice.php?operation=getchallenge&username=admin";
//JSON Node Names
private static final String TAG_RESULT = "result";
private static final String TAG_TOKEN = "token";
// contacts JSONArray
JSONArray contacts = null;
String token = null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.login);
if (android.os.Build.VERSION.SDK_INT > 9) {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
}
new AsyncTask<Void, Void, Void>() {
#SuppressWarnings("unused")
JSONObject result;
#Override
protected Void doInBackground(Void... params) {
// Creating new JSON Parser
JSONParser jParser = new JSONParser();
// Getting JSON from URL
JSONObject json = jParser.getJSONFromUrl(url);
try {
// Getting JSON Array
result = json.getJSONObject(TAG_RESULT);
JSONObject json_result = json.getJSONObject(TAG_RESULT);
// Storing JSON item in a Variable
token = json_result.getString(TAG_TOKEN);
//Importing TextView
} catch (JSONException e) {
e.printStackTrace();
}
String username="admin";
String accesskeyvalue = "**************";
String accessKey=md5(token + accesskeyvalue);
String data = null;
try {
data = URLEncoder.encode("username", "UTF-8")
+ "=" + URLEncoder.encode(username, "UTF-8");
data += "&" + URLEncoder.encode("accessKey", "UTF-8") + "="
+ URLEncoder.encode(accessKey, "UTF-8");
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
String text = "";
BufferedReader reader=null;
System.out.println(data);
// Send data
try
{
// Defined URL where to send data
URL url = new URL("http://***************/webservice.php?operation=login");
// Send POST data request
URLConnection conn = url.openConnection();
conn.setDoOutput(true);
OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
wr.write( data );
wr.flush();
// Get the server response
reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
StringBuilder sb = new StringBuilder();
String line = null;
// Read Server Response
while((line = reader.readLine()) != null)
{
// Append server response in string
sb.append(line + "\n");
}
text = sb.toString();
}
catch(Exception ex)
{
}
finally
{
try
{
reader.close();
}
catch(Exception ex) {}
}
// Show response
System.out.println(text);
String sessionid = text.substring(41, 62);
System.out.println(sessionid);
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
}
}.execute();
}
public String md5(String s)
{
MessageDigest digest;
try
{
digest = MessageDigest.getInstance("MD5");
digest.update(s.getBytes(),0,s.length());
String hash = new BigInteger(1, digest.digest()).toString(16);
return hash;
}
catch (NoSuchAlgorithmException e)
{
e.printStackTrace();
}
return "";
}
public void sendMessage(View view)
{
Intent intent = new Intent(Login.this, Quote1.class);
intent.putExtra("sessionId", sessionId);
startActivity(intent);
}
}
Here in sendMessage() I am not able to use sessionId as it is declared in doInBackground() which is protected.
I am bit weak in OOP.
Please help.

To access variables within a class between different methods simply make the variable a class variable.
To send data between activities refer to this article.
Basic example of Activity1 sending message to Activity2:
Activity1:
//Static String to identify the send parameter, without this this you have to set the exact same string twice.
public final static String SESSION_ID = "com.example.your.long.appname.SESSION_ID";
//sendMessage method is called for some reason in your class that you define (e.g user onClick)
public void sendMessage(View view) {
//Create an Intent
Intent intent = new Intent(this, Activity2.class);
//put the sessionID as extra intent.
intent.putExtra(SESSION_ID, sessionID);
//Start Activity2 with the intent.
startActivity(intent);
}
And to get the variable sent, use getStringExtra(String) for example in Activity2:
//Get the intent
Intent intent = getIntent();
//Get the message
String message = intent.getStringExtra(Activity1.SESSION_ID);

you can put your sessionId variable as a class variable in Login class as you did for TAG_RESULT, TAG_TOKEN etc...
Then, because your asyncTask is declared inline this Login class, you cann access it (and change its value) from it (the AsyncTask) and also access it's value in sendMessage method of the Login class.
I would also recommand (for better readability) to put you AsyncTask as another class (inner class of LoginClass). Code will be more readable.

Related

Async Task: class should be static or leaks might occur

I am trying to make a function that returns a json (using org.json dependencies) from a http request.
To do this in Android Java, it is necessary to create a AsyncTask
public class MainActivity extends AppCompatActivity {
TextView resultQuery;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
resultQuery = findViewById(R.id.resultQuery);
try {
new sendUrl().execute();
} catch (Exception e) {
e.printStackTrace();
resultQuery.setText("Erro: " + e);
Toast.makeText(this, "Erro" + e, Toast.LENGTH_SHORT).show();
}
}
private class sendUrl extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... params){
try {
call_me();
} catch (Exception e) {
e.printStackTrace();
}
return "";
}
#Override
protected void onPostExecute(String message){
Toast.makeText(MainActivity.this, "PostExecute", Toast.LENGTH_SHORT).show();
}
}
public void call_me() throws Exception {
String url = "https://api.github.com/users/leonanml";
URL obj = new URL(url);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
// optional default is GET
con.setRequestMethod("GET");
//add request header
con.setRequestProperty("User-Agent", "Mozilla/5.0");
int responseCode = con.getResponseCode();
//System.out.println("\nSending 'GET' request to URL : " + url);
Toast.makeText(this, "Response Code : " + responseCode, Toast.LENGTH_SHORT).show();
BufferedReader in = new BufferedReader(
new InputStreamReader(con.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
//print in String
//System.out.println(response.toString());
//Read JSON response and print
JSONObject myResponse = new JSONObject(response.toString());
//System.out.println("result after Reading JSON Response");
//System.out.println("id: "+myResponse.getString("login"));
resultQuery.setText(response.toString());
}}
Currently my "sendUrl" class is giving a warning :
This AsyncTask class should be static or leaks might occur (com.muller.httprequest.MainActivity.sendUrl) Inspection info:A static
field will leak contexts.
When you use an inner class that is not static, it can't be collected by the garbage collection so it's gonna keep using memory, easy fix is to just make the inner class static or make it out of the activity class.

Need to change String into JSON and return it. The code runs fine except I get the error: java.lang.String cannot be converted to JSONObject

Everything seems to be fine except for the JSON exception error.
Here it is specifically: org.json.JSONException:
Value username of type `java.lang.String` cannot be converted to `JSONObject`.
There are a number of other flags that I can check in logcat and everything seems pretty good except that. I think the problem is that I need to convert the String encodedStr into a JSON object and return it to ASYNC TASK.
private class AsyncDataClass extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... params) {
//Use HashMap, it works similar to NameValuePair
Map<String, String> dataToSend = new HashMap<>();
dataToSend.put("username", params[1]);
dataToSend.put("password", params[2]);
//Server Communication part - it's relatively long but uses standard methods
//Encoded String - we will have to encode string by our custom method (Very easy)
String encodedStr = getEncodedData(dataToSend);
//Will be used if we want to read some data from server
BufferedReader reader = null;
//Connection Handling
try {
//Converting address String to URL
URL url = new URL(serverUrl);
//Opening the connection (Not setting or using CONNECTION_TIMEOUT)
HttpURLConnection con = (HttpURLConnection) url.openConnection();
//Post Method
con.setRequestMethod("POST");
//To enable inputting values using POST method
//(Basically, after this we can write the dataToSend to the body of POST method)
con.setDoOutput(true);
OutputStreamWriter writer = new OutputStreamWriter(con.getOutputStream());
//Writing dataToSend to outputstreamwriter
writer.write(encodedStr);
//Sending the data to the server - This much is enough to send data to server
//But to read the response of the server, you will have to implement the procedure below
writer.flush();
//Data Read Procedure - Basically reading the data comming line by line
StringBuilder sb = new StringBuilder();
reader = new BufferedReader(new InputStreamReader(con.getInputStream()));
String line;
while ((line = reader.readLine()) != null) { //Read till there is something available
sb.append(line + "\n"); //Reading and saving line by line - not all at once
}
line = sb.toString();//Saving complete data received in string, you can do it differently
//Just check to the values received in Logcat
Log.i("custom_check", "The values received in the store part are as follows:");
Log.i("custom_check", line);
} catch (Exception e) {
e.printStackTrace();
} finally {
if (reader != null) {
try {
reader.close(); //Closing the
} catch (IOException e) {
e.printStackTrace();
}
}
}
//Same return null, but if you want to return the read string (stored in line)
//then change the parameters of AsyncTask and return that type, by converting
//the string - to say JSON or user in your case
**strong text**return encodedStr;**strong text**
**strong text**HERE IS THE PROBLEM I BELIEVE.
}
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
System.out.println("Resulted Value: " + result);
if (result.equals("") || result == null) {
Toast.makeText(MainActivity.this, "Server connection failed", Toast.LENGTH_LONG).show();
return;
}
int jsonResult = returnParsedJsonObject(result);
if (jsonResult == 0) {
Toast.makeText(MainActivity.this, "Invalid username or password", Toast.LENGTH_LONG).show();
return;
}
if (jsonResult == 1) {
Intent intent = new Intent(MainActivity.this, LoginActivity.class);
intent.putExtra("USERNAME", enteredUsername);
intent.putExtra("MESSAGE", "You have been successfully login");
startActivity(intent);
}
}
private int returnParsedJsonObject(String result) {
JSONObject resultObject = null;
int returnedResult = 0;
try {
resultObject = new JSONObject(result);
returnedResult = resultObject.getInt("success");
} catch (JSONException e) {
e.printStackTrace();
}
return returnedResult;
}
}
private StringBuilder inputStreamToString(InputStream is) {
String rLine = "";
StringBuilder answer = new StringBuilder();
BufferedReader br = new BufferedReader(new InputStreamReader(is));
try {
while ((rLine = br.readLine()) != null) {
answer.append(rLine);
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return answer;
}
//************getEncodedData*****************//
private String getEncodedData(Map<String,String> data) {
StringBuilder sb = new StringBuilder();
for(String key : data.keySet()) {
String value = null;
try {
value = URLEncoder.encode(data.get(key), "UTF-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
if(sb.length()>0)
sb.append("&");
sb.append(key + "=" + value);
}
return sb.toString();
}`enter code here`

How to Cache Json data to be available offline?

I have parsed the JSON Data in a listview and now I want to make it available offline.
Is there a way to save the JSON data at the phone so that you can see the data if your phone is offline?
Does someone knows an example?
EDIT works now:
public class MainActivity extends ListActivity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
new TheTask().execute();
}
class TheTask extends AsyncTask<Void, Void, JSONArray> {
InputStream is = null;
String result = "";
JSONArray jArray = null;
ProgressDialog pd;
#Override
protected void onPostExecute(JSONArray result) {
super.onPostExecute(result);
pd.dismiss();
ArrayList<String> list= new ArrayList<String>();
try {
for(int i=0;i<result.length();i++) {
JSONObject jb = result.getJSONObject(i) ;
String name = jb.getString("name")+" "+jb.getString("Art");
list.add(name);
}
} catch(Exception e) {
e.printStackTrace();
}
setListAdapter(new ArrayAdapter<String>(MainActivity.this, android.R.layout.simple_list_item_1, list));
}
#Override
protected void onPreExecute() {
super.onPreExecute();
pd = ProgressDialog.show(MainActivity.this, "State",
"Loading...", true);
}
#Override
protected JSONArray doInBackground(Void... arg0) {
ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
try {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("***");
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
} 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();
writeToFile(result);
} catch (Exception e) {
Log.e("log_tag", "Error converting result " + e.toString());
}
try {
jArray = new JSONArray(result);
} catch (JSONException e) {
Log.e("log_tag", "Error parsing data " + e.toString());
}
try {
jArray = new JSONArray(readFromFile());
} catch (JSONException e) {
Log.e("log_tag", "Error parsing data " + e.toString());
}
return jArray;
}
}
private void writeToFile(String data) {
try {
OutputStreamWriter outputStreamWriter = new OutputStreamWriter(openFileOutput("config.txt", Context.MODE_PRIVATE));
outputStreamWriter.write(data);
outputStreamWriter.close();
}
catch (IOException e) {
Log.e("Exception", "File write failed: " + e.toString());
}
}
private String readFromFile() {
String ret = "";
try {
InputStream inputStream = openFileInput("config.txt");
if ( inputStream != null ) {
InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
String receiveString = "";
StringBuilder stringBuilder = new StringBuilder();
while ( (receiveString = bufferedReader.readLine()) != null ) {
stringBuilder.append(receiveString);
}
inputStream.close();
ret = stringBuilder.toString();
}
} catch (FileNotFoundException e) {
Log.e("login activity", "File not found: " + e.toString());
} catch (IOException e) {
Log.e("login activity", "Can not read file: " + e.toString());
}
return ret;
}
}
You have two ways. Either you create a database and save all of the data there and retrieve it back when you want to. Or if the data you have is not that much and you don't want to deal with databases, then you write the json string to a text file in the memory card and read it later when you are offline.
And for the second case, every time you go online, you can retrieve the same json from your web service and over write it to the old one. This way you can be sure that you have the latest json saved to the device.
this class will help you cache strings in files with a key to retrieve later on. the string can be a json string and key can be the url you requested and also an identifier for the url if you are using post method.
public class CacheHelper {
static int cacheLifeHour = 7 * 24;
public static String getCacheDirectory(Context context){
return context.getCacheDir().getPath();
}
public static void save(Context context, String key, String value) {
try {
key = URLEncoder.encode(key, "UTF-8");
File cache = new File(getCacheDirectory(context) + "/" + key + ".srl");
ObjectOutput out = new ObjectOutputStream(new FileOutputStream(cache));
out.writeUTF(value);
out.close();
} catch (Exception e) {
e.printStackTrace();
}
}
public static void save(Context context, String key, String value, String identifier) {
save(context, key + identifier, value);
}
public static String retrieve(Context context, String key, String identifier) {
return retrieve(context, key + identifier);
}
public static String retrieve(Context context, String key) {
try {
key = URLEncoder.encode(key, "UTF-8");
File cache = new File(getCacheDirectory(context) + "/" + key + ".srl");
if (cache.exists()) {
Date lastModDate = new Date(cache.lastModified());
Date now = new Date();
long diffInMillisec = now.getTime() - lastModDate.getTime();
long diffInSec = TimeUnit.MILLISECONDS.toSeconds(diffInMillisec);
diffInSec /= 60;
diffInSec /= 60;
long hours = diffInSec % 24;
if (hours > cacheLifeHour) {
cache.delete();
return "";
}
ObjectInputStream in = new ObjectInputStream(new FileInputStream(cache));
String value = in.readUTF();
in.close();
return value;
}
} catch (Exception e) {
e.printStackTrace();
}
return "";
}
}
how to use it :
String string = "cache me!";
String key = "cache1";
CacheHelper.save(context, key, string);
String getCache = CacheHelper.retrieve(context, key); // will return 'cache me!'
Once you download the data you could persist the data on the mobile, using a database or a system of your preference.
You can check the different options here: data-storage
using SharedPreferences should be prepared to sqlite (unless of course you have a database structure). For caching and storing data pulled from the internet, I recommend robospice: https://github.com/octo-online/robospice. It's a very well done library, easy to use, and should be used any time you download data from the internet or have a long-running task.
You can use those two methods two store you JSON file as a string in your SharedPreferences and retrieve it back:
public String getStringProperty(String key) {
sharedPreferences = context.getSharedPreferences("preferences", Activity.MODE_PRIVATE);
String res = null;
if (sharedPreferences != null) {
res = sharedPreferences.getString(key, null);
}
return res;
}
public void setStringProperty(String key, String value) {
sharedPreferences = context.getSharedPreferences("preferences", Activity.MODE_PRIVATE);
if (sharedPreferences != null) {
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString(key, value);
editor.commit();
CupsLog.i(TAG, "Set " + key + " property = " + value);
}
}
Just use setStringProperty("json", "yourJsonString") to save and getStringProperty("json") to retrieve.
How to Cache Json data to be available offline?
You can use gson to parse JSON data more easily.
In your build.gradle file add this dependency.
compile 'com.google.code.gson:gson:2.8.0'
Then create a POJO class to parse JSON data.
Example POJO class:
public class AppGeneralSettings {
#SerializedName("key1")
String data;
public String getData() {
return data;
}
}
To parse a json string from internet use this snippet
AppGeneralSettings data=new Gson().fromJson(jsonString, AppGeneralSettings.class);
Then add a helper class to store and retrieve JSON data to and from preferences.
Example: Helper class to store data
public class AppPreference {
private static final String FILE_NAME = BuildConfig.APPLICATION_ID + ".apppreference";
private static final String APP_GENERAL_SETTINGS = "app_general_settings";
private final SharedPreferences preferences;
public AppPreference(Context context) {
preferences = context.getSharedPreferences(FILE_NAME, MODE_PRIVATE);
}
public SharedPreferences.Editor setGeneralSettings(AppGeneralSettings appGeneralSettings) {
return preferences.edit().putString(APP_GENERAL_SETTINGS, new Gson().toJson(appGeneralSettings));
}
public AppGeneralSettings getGeneralSettings() {
return new Gson().fromJson(preferences.getString(APP_GENERAL_SETTINGS, "{}"), AppGeneralSettings.class);
}
}
To save data
new AppPreference().setGeneralSettings(appGeneralSettings).commit();
To retrieve data
AppGeneralSettings appGeneralSettings = new AppPreference().getGeneralSettings();
You can cache your Retrofit responses, so when you make the same request second time, Retrofit will take it from it's cache:
https://medium.com/#coreflodev/understand-offline-first-and-offline-last-in-android-71191e92b426, https://futurestud.io/tutorials/retrofit-2-activate-response-caching-etag-last-modified. After that you'l need to parse that json again

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 !!

JSONException: no value for data

I want to fetch json data from this link: link
& here is my code for that:
private static String url = "https://graph.facebook.com/fql?q=SELECT%20url,%20normalized_url,%20share_count,%20like_count,%20comment_count,%20total_count,%20commentsbox_count,%20comments_fbid,%20click_count%20FROM%20link_stat%20WHERE%20url=%27https://www.facebook.com/BillionHands%27";
// JSON Node names
private static final String TAG_DATA = "data";
private static final String TAG_SHARE = "share_count";
private static final String TAG_LIKE = "like_count";
private TextView LikeTv;
public String like;
JSONArray data = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_about_us);
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
// Creating JSON Parser instance
JSONParser jParser = new JSONParser();
// getting JSON string from URL
JSONObject json = jParser.getJSONFromUrl(url);
try {
// Getting Array of Contacts
data = json.getJSONArray(TAG_DATA);
JSONObject c = data.getJSONObject(0);
// Storing each json item in variable
String share = c.getString(TAG_SHARE);
like = c.getString(TAG_LIKE);
Log.i("Like Count",like);
} catch (JSONException e) {
e.printStackTrace();
}
LikeTv = (TextView) findViewById(R.id.tvLike);
LikeTv.setText(like);
Now I am getting "JSONException: no value for data" Please help... whats wrong in my code..
Well....
I got your problem solution...
The method you wrote getJSONFromUrl()..
I am sure it contains HttpPost object..
change that to HttpGet and it will start working...
EDIT
Here is the code I tried with
public class MainActivity extends Activity {
private static String url = "https://graph.facebook.com/fql?q=SELECT%20url,%20normalized_url,%20share_count,%20like_count,%20comment_count,%20total_count,%20commentsbox_count,%20comments_fbid,%20click_count%20FROM%20link_stat%20WHERE%20url=%27https://www.facebook.com/BillionHands%27";
// JSON Node names
private static final String TAG_DATA = "data";
private static final String TAG_SHARE = "share_count";
private static final String TAG_LIKE = "like_count";
private TextView LikeTv;
public String like;
JSONArray data = null;
#SuppressLint("NewApi")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
// Creating JSON Parser instance
JSONParser jParser = new JSONParser();
// getting JSON string from URL
JSONObject json = jParser.getJSONfromURL(url);
try {
// Getting Array of Contacts
Log.d("JSON ","DATA "+json);
data = json.getJSONArray(TAG_DATA);
JSONObject c = data.getJSONObject(0);
// Storing each json item in variable
String share = c.getString(TAG_SHARE);
like = c.getString(TAG_LIKE);
Log.i("Like Count",like);
} catch (JSONException e) {
e.printStackTrace();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
}
class JSONParser
{
public JSONObject getJSONfromURL(String url) {
InputStream is = null;
String result = "";
JSONObject jArray = null;
// http post
try {
HttpClient httpclient = new DefaultHttpClient();
HttpGet httpget = new HttpGet(url);
HttpResponse response = httpclient.execute(httpget);
HttpEntity entity = response.getEntity();
is = entity.getContent();
} 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 get data string ",
"Error converting result " + e.toString());
}
try {
jArray = new JSONObject(result);
} catch (JSONException e) {
Log.e("log_tag create object ",
"Error parsing data " + e.toString());
}
return jArray;
}
}
The "data" element in your JSON isn't an array, it is a JSONobject. So instead of:
JSONArray data = json.getJSONArray(TAG_DATA);
Try this:
JSONObject data = json.getJSONObject(TAG_DATA);
From the JSONObject, you can get items like TAG_SHARE and TAG_LIKE.
Good luck!

Categories