vendredi 6 mars 2015

JSONException : No value for data



I am trying to gets posts data from a facebook page. But it is showing no data in json object. Facebook only let us access data when we have access token which I have mentioned in the code. Still its returning no data. Here are my classes:



MainActivity.java



import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;

import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.facebook.android.DialogError;
import com.facebook.android.Facebook;
import com.facebook.android.Facebook.DialogListener;
import com.facebook.android.FacebookError;
import com.facebook.android.Util;


public class MainActivity extends Activity implements OnClickListener {


ImageView pic, fbbutton;
TextView welcome;
Facebook fb;
public SharedPreferences sp;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);

setContentView(R.layout.activity_main);

welcome = (TextView)findViewById(R.id.textView1);

String APP_ID = getString(R.string.APP_ID);
fb = new Facebook(APP_ID);

sp=getPreferences(MODE_PRIVATE);
String access_token =sp.getString(("access_token"), null);
long expires = sp.getLong("access_expires", 1);

if(access_token!=null){
fb.setAccessToken(access_token);
}
if(expires!=0){
fb.setAccessExpires(expires);
}



fbbutton= (ImageView) findViewById(R.id.imageView1);
pic=(ImageView)findViewById(R.id.imageView2);
fbbutton.setOnClickListener(this);
try {
updateButtonImage();
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}


@SuppressWarnings("deprecation")
private void updateButtonImage() throws MalformedURLException, IOException {
// TODO Auto-generated method stub
if(fb.isSessionValid()){
fbbutton.setImageResource(R.drawable.logout_button);


//parsing data from facebook
JSONObject obj = null;
URL img_url = null;
//getting name from facebook
String jsonUser = fb.request("me");
try {
obj = Util.parseJson(jsonUser);
} catch (FacebookError e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

String id = obj.optString("id");
String name = obj.optString("name");
welcome.setText("Welcome, "+name);

//getting image from facebook
img_url = new URL("http://ift.tt/rrPc6B"+id+"/picture?type=normal");
Bitmap bmp = BitmapFactory.decodeStream(img_url.openConnection().getInputStream());
pic.setImageBitmap(bmp);

//making image visible
pic.setVisibility(ImageView.VISIBLE);

//getting json data from url





}else{
fbbutton.setImageResource(R.drawable.login_button);
pic.setVisibility(ImageView.INVISIBLE);
}
}


@SuppressWarnings("deprecation")
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
if(fb.isSessionValid()){
try {
fb.logout(getApplicationContext());
updateButtonImage();
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}else{
//login
fb.authorize(MainActivity.this, new DialogListener() {

@Override
public void onFacebookError(FacebookError e) {
// TODO Auto-generated method stub
Toast.makeText(MainActivity.this, "OnFbError", Toast.LENGTH_SHORT);
}

@Override
public void onError(DialogError e) {
// TODO Auto-generated method stub
Toast.makeText(MainActivity.this, "OnError", Toast.LENGTH_SHORT);
}

@Override
public void onComplete(Bundle values) {
// TODO Auto-generated method stub
Toast.makeText(MainActivity.this, "OnComplete", Toast.LENGTH_SHORT);
Editor editor=sp.edit();
editor.putString("access_token", fb.getAccessToken());
editor.putLong("access_expires", fb.getAccessExpires());
editor.commit();
try {
updateButtonImage();
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Intent i = new Intent(MainActivity.this, NewsFeed.class);
startActivity(i);

}

@Override
public void onCancel() {
// TODO Auto-generated method stub
Toast.makeText(MainActivity.this, "OnCancel", Toast.LENGTH_SHORT);
}
});
}
}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// TODO Auto-generated method stub
super.onActivityResult(requestCode, resultCode, data);
fb.authorizeCallback(requestCode, resultCode, data);

}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}



}


NewsFeed.java



import java.util.ArrayList;
import java.util.HashMap;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.ListActivity;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;

public class NewsFeed extends ListActivity {

private ProgressDialog pDialog;
// json url
public static String url = "http://ift.tt/1Gs0e9M";

// json tags
// JSON Node names
private static final String TAG_DATA = "data";
private static final String TAG_ID = "id";
private static final String TAG_MESSAGE = "message";
private static final String TAG_CREATETIME = "created_time";

// contacts JSONArray
JSONArray contacts = null;

// Hashmap for ListView
ArrayList<HashMap<String, String>> contactList;

@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);

setContentView(R.layout.news_feed);
contactList = new ArrayList<HashMap<String, String>>();

ListView lv = getListView();
// Calling async task to get json
new GetContacts().execute();
}

private class GetContacts extends AsyncTask<Void, Void, Void> {

@Override
protected void onPreExecute() {
super.onPreExecute();
// Showing progress dialog
pDialog = new ProgressDialog(NewsFeed.this);
pDialog.setMessage("Please wait...");
pDialog.setCancelable(false);
pDialog.show();

}

@Override
protected Void doInBackground(Void... arg0) {
// Creating service handler class instance
ServiceHandler sh = new ServiceHandler();

// Making a request to url and getting response
String jsonStr = sh.makeServiceCall(url, ServiceHandler.GET);

Log.d("Response: ", "> " + jsonStr);

if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);

// Getting JSON Array node
contacts = jsonObj.getJSONArray(TAG_DATA);

// looping through All Contacts
for (int i = 0; i < contacts.length(); i++) {
JSONObject c = contacts.getJSONObject(i);

String id = c.getString(TAG_ID);
String message = c.getString(TAG_MESSAGE);//feed
String createtime = c.getString(TAG_CREATETIME);//date, time created

// // Phone node is JSON Object
// JSONObject phone = c.getJSONObject(TAG_PHONE);
// String mobile = phone.getString(TAG_PHONE_MOBILE);
// String home = phone.getString(TAG_PHONE_HOME);
// String office = phone.getString(TAG_PHONE_OFFICE);

// tmp hashmap for single contact
HashMap<String, String> data = new HashMap<String, String>();

// adding each child node to HashMap key => value
data.put(TAG_ID, id);
data.put(TAG_MESSAGE, message);
data.put(TAG_CREATETIME, createtime);

// adding contact to contact list
contactList.add(data);
}
} catch (JSONException e) {
e.printStackTrace();
}
} else {
Log.e("ServiceHandler", "Couldn't get any data from the url");
}

return null;
}

@Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
// Dismiss the progress dialog
if (pDialog.isShowing())
pDialog.dismiss();
/**
* Updating parsed JSON data into ListView
* */
ListAdapter adapter = new SimpleAdapter(
NewsFeed.this, contactList,
R.layout.list_item, new String[] { TAG_MESSAGE, TAG_CREATETIME,
}, new int[] { R.id.message,
R.id.time });

setListAdapter(adapter);
}

}
}


ServiceHandler.java



import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.List;

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.client.utils.URLEncodedUtils;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;

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) {
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;

}


}



Aucun commentaire:

Enregistrer un commentaire