Graph Facebook won't retrieve data - android

I'm trying to retrieve data from Facebook using graph Facebook, like Profile Pic, Gender, Age, Name, ID & Link, I'm getting Facebook Profile Pic only successfully but other won't retrieved. Please help!
MainActivity.java
package com.example.facebookprofile;
import org.json.JSONException;
import org.json.JSONObject;
import com.example.facebookprofile.pictureAsync.onImageDownloaded;
import com.example.facebookprofile.profileAsync.profileImplement;
import android.app.Activity;
import android.app.ProgressDialog;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends Activity implements profileImplement, onImageDownloaded {
ProgressDialog dialog;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
public void onClick(View view){
EditText enterUsername = (EditText) findViewById(R.id.enterUsername);
String s = "https://graph.facebook.com/" + enterUsername.getEditableText().toString();
pictureAsync picTask = new pictureAsync(this);
profileAsync task = new profileAsync(this);
picTask.execute(s + "/picture?type=large");
picTask.delegate = this;
task.delegate = this;
task.execute(s);
}
public static User parseJSON(String jsonString) throws JSONException{
JSONObject top = new JSONObject(jsonString);
String name = "NA";
if(top.has("name"))
name = top.getString("name");
String username = top.getString("username");
String id = "NA";
if(top.has("id"))
id = top.getString("id");
String gender = "NA";
if(top.has("gender"))
gender = top.getString("gender");
String link = "https://www.facebook.com/"+username;
if(top.has("link"))
link = top.getString("link");
User output = new User(name, username, id, gender, link);
return output;
}
#Override
public void update(User user) {
// TODO Auto-generated method stub
if(user == null){
Toast t = Toast.makeText(this, "Invalid username", Toast.LENGTH_SHORT);
t.show();
}
else{
TextView name = (TextView) findViewById(R.id.name);
TextView id = (TextView) findViewById(R.id.id);
TextView gender = (TextView) findViewById(R.id.gender);
TextView link = (TextView) findViewById(R.id.link);
name.setText(user.name);
id.setText(user.id);
gender.setText(user.gender);
link.setText(user.link);
}
}
#Override
public void setImage(Bitmap bitmap) {
// TODO Auto-generated method stub
if(bitmap != null){
ImageView image = (ImageView) findViewById(R.id.imageView1);
image.setImageBitmap(bitmap);
}
}
}
pictureAsync.java
package com.example.facebookprofile;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import javax.net.ssl.HttpsURLConnection;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
public class pictureAsync extends AsyncTask<String, Integer, Bitmap> {
Context context;
onImageDownloaded delegate;
public interface onImageDownloaded{
public void setImage(Bitmap bitmap);
}
public pictureAsync(Context context) {
this.context = context;
}
#Override
protected Bitmap doInBackground(String... params) {
String picUrl = params[0];
try {
URL url = new URL(picUrl);
HttpsURLConnection connection = (HttpsURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.connect();
InputStream input = connection.getInputStream();
Bitmap myBitmap = BitmapFactory.decodeStream(input);
return myBitmap;
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Bitmap result) {
super.onPostExecute(result);
if(delegate!=null)
delegate.setImage(result);
}
}
profileAsync.java
package com.example.facebookprofile;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Scanner;
import javax.net.ssl.HttpsURLConnection;
import org.json.JSONException;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.os.AsyncTask;
public class profileAsync extends AsyncTask<String, Integer, User> {
profileImplement delegate;
Context context;
ProgressDialog dialog;
public profileAsync(Context context) {
this.context = context;
}
#Override
public void onPreExecute() {
super.onPreExecute();
dialog = new ProgressDialog(context);
dialog.setMessage("Loading...Please wait");
dialog.show();
}
public interface profileImplement{
public void update(User user);
}
#Override
protected User doInBackground(String... arg) {
String user = arg[0];
try {
URL url = new URL(user);
HttpsURLConnection connection = (HttpsURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.connect();
InputStream input = connection.getInputStream();
if(input == null) return null;
Scanner networkScanner = new Scanner(input);
StringBuffer buffer = new StringBuffer();
int count = 0;
while(networkScanner.hasNext()){
String line = networkScanner.next();
count += line.length();
//publishProgress(count);
buffer.append(line);
}
networkScanner.close();
return MainActivity.parseJSON(buffer.toString());
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(User result) {
dialog.dismiss();
if(delegate != null)
delegate.update(result);
}
// protected void onProgressUpdate(Integer... values) {
// // TODO Auto-generated method stub
// super.onProgressUpdate(values);
// dialog.setMessage("downloaded: " + values[0]);
// }
}
User.java
package com.example.facebookprofile;
public class User {
String name;
String username;
String id;
String gender;
String link;
User(String name, String username , String id , String gender , String link){
this.name = name;
this.username = username;
this.id = id;
this.gender = gender;
this.link = link;
}
}

It is a feature gone deprecated.

Related

Progressbar with Async Task while trying to connect to server

I want to show Progress Dialog when background task is executed by doInbackground Method of AsyncTask Class, But the problem is when my server is off (Wamp server turns off) it doesnot shows Progress Dialog when trying to get connected with the server.
Please Help in this regard.
Main Class:
import android.app.AlertDialog;
import android.database.Cursor;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.Spinner;
import android.widget.Toast;
import java.util.Calendar;
import java.util.Date;
import java.text.SimpleDateFormat;
import java.util.concurrent.ExecutionException;
public class MainActivity extends AppCompatActivity{
Button btnSubmitOrder;
EditText edDealerID;
EditText edProductID;
EditText edQuantity;
String stDealerID;
String stProductID;
String stQuantity;
String stUnit;
String stDate;
String stTime;
String stStatus;
ProgressBar edProgress;
Date currentDate = Calendar.getInstance().getTime();
DatabaseSQLite objDatabaseSqlite;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Date objDate = Calendar.getInstance().getTime();
SimpleDateFormat df = new SimpleDateFormat("dd/MMM/yyyy");
stDate = df.format(objDate);
SimpleDateFormat sdf = new SimpleDateFormat("hh:mm a");
stTime = sdf.format(objDate);
final Spinner dropdown = findViewById(R.id.edit_unit);
String[] items = new String[]{"Box", "Packets"};
ArrayAdapter<String> adapter = new ArrayAdapter<>(this, android.R.layout.simple_spinner_dropdown_item, items);
dropdown.setAdapter(adapter);
objDatabaseSqlite = new DatabaseSQLite(this);
btnSubmitOrder = findViewById(R.id.btn_submitorder);
edDealerID = findViewById(R.id.edit_dealerid);
edProductID = findViewById(R.id.edit_productid);
edQuantity = findViewById(R.id.edit_quantity);
edProgress = findViewById(R.id.ed_progress);
btnSubmitOrder.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
stDealerID = edDealerID.getText().toString();
stProductID = edProductID.getText().toString();
stQuantity = edQuantity.getText().toString();
stUnit = dropdown.getSelectedItem().toString();
stStatus = "Pending";
BackgroundTask objBackground = new BackgroundTask(MainActivity.this);
try {
String response = objBackground.execute(stDealerID, stProductID, stQuantity, stUnit, stDate, stTime, stStatus).get();
} catch (ExecutionException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
}
}
BackgroundTask Class:
import android.app.ProgressDialog;
import android.content.Context;
import android.os.AsyncTask;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;
/**
* Created by Saffi on 3/17/2016.
*/
public class BackgroundTask extends AsyncTask<String,Void,String> {
private String response = "";
private ProgressDialog dialog;
Context ctx;
BackgroundTask(Context ctx)
{
this.ctx = ctx;
}
#Override
protected void onPreExecute() {
dialog = new ProgressDialog(ctx);
dialog.setMessage("Progress start");
dialog.show();
}
protected String doInBackground(String... params) {
String sendInvoice = "http://10.0.2.2/YounasTraders/SendInvoice.php";
String dealerId = params[0];
String productId = params[1];
String quantity = params[2];
String unit = params[3];
String date = params[4];
String time = params[5];
String status = params[6];
try {
URL objurl = new URL(sendInvoice);
HttpURLConnection objhttpurlconnection = (HttpURLConnection) objurl.openConnection();
objhttpurlconnection.setRequestMethod("POST");
objhttpurlconnection.setDoOutput(true);
objhttpurlconnection.setDoInput(true);
OutputStream objos = objhttpurlconnection.getOutputStream();
BufferedWriter objbuffwrite = new BufferedWriter(new OutputStreamWriter(objos, "UTF-8"));
String data = URLEncoder.encode("dealer_id", "UTF-8") +"="+URLEncoder.encode(dealerId, "UTF-8")+"&"+
URLEncoder.encode("product_id", "UTF-8")+"="+URLEncoder.encode(productId, "UTF-8")+"&"+
URLEncoder.encode("quantity", "UTF-8")+"="+URLEncoder.encode(quantity, "UTF-8")+"&"+
URLEncoder.encode("unit", "UTF-8")+"="+URLEncoder.encode(unit, "UTF-8")+"&"+
URLEncoder.encode("date", "UTF-8")+"="+URLEncoder.encode(date, "UTF-8")+"&"+
URLEncoder.encode("time", "UTF-8")+"="+URLEncoder.encode(time, "UTF-8")+"&"+
URLEncoder.encode("status", "UTF-8")+"="+URLEncoder.encode(status, "UTF-8");
objbuffwrite.write(data);
objbuffwrite.flush();
objbuffwrite.close();
objos.close();
InputStream objis = objhttpurlconnection.getInputStream();
objis.close();
objhttpurlconnection.disconnect();
response = "Order Sent Successfully";
return response;
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
response = "Order Not Sent Successfully";
return response;
}
#Override
protected void onProgressUpdate(Void... values) {
super.onProgressUpdate(values);
dialog.show();
}
#Override
protected void onPostExecute(String value) {
dialog.dismiss();
}
}
The problem is you are executing a task on main thread using .get method
The first change your AsyncTask task include this callback interface to call it after finishing your HTTP request
public class BackgroundTask extends AsyncTask {
private CallBack callBack;
public CallBack getCallBack() {
return callBack;
}
public void setCallBack(CallBack callBack) {
this.callBack = callBack;
}
private String response = "";
private ProgressDialog dialog;
Context ctx;
BackgroundTask(Context ctx)
{
this.ctx = ctx;
}
#Override
protected void onPreExecute() {
dialog = new ProgressDialog(ctx);
dialog.setMessage("Progress start");
dialog.show();
}
protected String doInBackground(String... params) {
String sendInvoice = "http://10.0.2.2/YounasTraders/SendInvoice.php";
String dealerId = params[0];
String productId = params[1];
String quantity = params[2];
String unit = params[3];
String date = params[4];
String time = params[5];
String status = params[6];
try {
URL objurl = new URL(sendInvoice);
HttpURLConnection objhttpurlconnection = (HttpURLConnection) objurl.openConnection();
objhttpurlconnection.setRequestMethod("POST");
objhttpurlconnection.setDoOutput(true);
objhttpurlconnection.setDoInput(true);
OutputStream objos = objhttpurlconnection.getOutputStream();
BufferedWriter objbuffwrite = new BufferedWriter(new OutputStreamWriter(objos, "UTF-8"));
String data = URLEncoder.encode("dealer_id", "UTF-8") +"="+URLEncoder.encode(dealerId, "UTF-8")+"&"+
URLEncoder.encode("product_id", "UTF-8")+"="+URLEncoder.encode(productId, "UTF-8")+"&"+
URLEncoder.encode("quantity", "UTF-8")+"="+URLEncoder.encode(quantity, "UTF-8")+"&"+
URLEncoder.encode("unit", "UTF-8")+"="+URLEncoder.encode(unit, "UTF-8")+"&"+
URLEncoder.encode("date", "UTF-8")+"="+URLEncoder.encode(date, "UTF-8")+"&"+
URLEncoder.encode("time", "UTF-8")+"="+URLEncoder.encode(time, "UTF-8")+"&"+
URLEncoder.encode("status", "UTF-8")+"="+URLEncoder.encode(status, "UTF-8");
objbuffwrite.write(data);
objbuffwrite.flush();
objbuffwrite.close();
objos.close();
InputStream objis = objhttpurlconnection.getInputStream();
objis.close();
objhttpurlconnection.disconnect();
response = "Order Sent Successfully";
return response;
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
response = "Order Not Sent Successfully";
return response;
}
#Override
protected void onProgressUpdate(Void... values) {
super.onProgressUpdate(values);
dialog.show();
}
#Override
protected void onPostExecute(String value) {
dialog.dismiss();
if(callBack != null)
callBack.onResult(value);
}
public interface CallBack{
void onResult(String value);
}
}
Second change execution of your async task, get result on callback
BackgroundTask objBackground = new BackgroundTask(MainActivity.this);
objBackground.setCallBack(new BackgroundTask.CallBack() {
#Override
public void onResult(String value) {
//get here your response
}
});
objBackground.execute(stDealerID, stProductID, stQuantity, stUnit, stDate, stTime, stStatus);

Data is not inserting into database of webhost from android

My data is not inserting to database of webhost.
Here is my ActionActivity.java from where I will send data to the database.
import android.app.Activity;
import android.content.Context;
import android.provider.Settings;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import java.io.InputStream;
public class ActionActivity extends Activity {
private String t;
TextView timer;
EditText e1,e2;
Button save;
static InputStream is = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_action);
Bundle time = getIntent().getExtras();
t = (String) time.get("com.example.masba.timemanagement.MESSAGE");
e1 = (EditText) findViewById(R.id.editText);
e1.setText(t, TextView.BufferType.EDITABLE);
e2 = (EditText) findViewById(R.id.editText2);
save = (Button) findViewById(R.id.save);
}
public void insert(View view){
String actionName = e1.getText().toString();
String time = e2.getText().toString();
Toast.makeText(this, "Data Inserting...", Toast.LENGTH_SHORT).show();
new SignupActivity(this).execute(actionName, time);
e1.setText("");
e2.setText("");
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.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();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
Now my SignupActivity.java Which extends Asynctask.
import android.content.Context;
import android.os.AsyncTask;
import android.widget.Toast;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
public class SignupActivity extends AsyncTask<String, Void, String> {
private Context context;
public SignupActivity(Context context) {
this.context = context;
}
protected void onPreExecute() {
}
#Override
protected String doInBackground(String... arg0) {
String actionName = arg0[0];
String time = arg0[1];
String link;
String data;
BufferedReader bufferedReader;
String result;
try {
data = "?actioname=" + URLEncoder.encode(actionName, "UTF-8");
data += "&time=" + URLEncoder.encode(time, "UTF-8");
link = "http://masumalmasba.comli.com/insertdata.php" + data;
URL url = new URL(link);
HttpURLConnection con = (HttpURLConnection) url.openConnection();
bufferedReader = new BufferedReader(new InputStreamReader(con.getInputStream()));
result = bufferedReader.readLine();
return result;
} catch (Exception e) {
return new String("Exception: " + e.getMessage());
}
}
#Override
protected void onPostExecute(String result) {
String jsonStr = result;
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
String query_result = jsonObj.getString("query_result");
if (query_result.equals("SUCCESS")) {
Toast.makeText(context, "Data inserted successfully.", Toast.LENGTH_SHORT).show();
} else if (query_result.equals("FAILURE")) {
Toast.makeText(context, "Data could not be inserted.", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(context, "Couldn't connect to remote database.", Toast.LENGTH_SHORT).show();
}
} catch (JSONException e) {
e.printStackTrace();
Toast.makeText(context, "Error parsing JSON data.", Toast.LENGTH_SHORT).show();
}
} else {
Toast.makeText(context, "Couldn't get any JSON data.", Toast.LENGTH_SHORT).show();
}
}
}
Now my insertdata.php code is:
<?php
$servername="mysql6.000webhost.com";
$username = "a1871724_masum";
$password = "almasba012";
$dbname = "a1871724_actiont";
$conn = new mysqli($servername , $username , $password , $dbname);
if($conn->connect_error)
{
die("Connection Failed: ".$conn->connect_error);
}
$action = $_GET['actionname'];
$time = $_GET['time'];
$sql = "INSERT INTO actiontime (name,time) VALUES ('($action)','($time)')";
if($conn->query($sql)===TRUE){
echo "New record created succesfully";
}
else{
echo "Error";
mysql_close($conn);
}
?>

When I tap the refresh button the images never appear

I have been trying too hard to get around this problom, when I tap the refresh button in my app, the images doesn't load on the screen.
This the DataFragment file, when i build this app there are no errors.
package com.example.popularmovis;
import android.app.Fragment;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.GridView;
import android.os.AsyncTask;
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.net.HttpURLConnection;
import java.net.URL;
import java.util.jar.JarException;
/**
* A placeholder fragment containing a simple view.
*/
public class DataFragment extends Fragment {
public ImageAdapter display;
public DataFragment() {
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Add this line in order for this fragment to handle menu events.
setHasOptionsMenu(true);
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.datafragment_menu, menu);
}
#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();
//noinspection SimplifiableIfStatement
if (id == R.id.action_refresh) {
FetchMovieData movieData = new FetchMovieData();
movieData.execute();
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public View onCreateView (LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container, false);
display = new ImageAdapter(rootView.getContext());
GridView gridView = (GridView) rootView.findViewById(R.id.gridView_movies);
gridView.setAdapter(display); // uses the view to get the context instead of getActivity().
return rootView;
}
public class FetchMovieData extends AsyncTask<Void, Void, String[]>{
private final String LOG_TAG = FetchMovieData.class.getSimpleName();
private String[] extractdisplayFromJason(String jasnData)
throws JSONException{
//These jason display need to be extracted
final String movie_results = "results";
final String movie_poster = "poster_path";
JSONObject movieData = new JSONObject(jasnData);
JSONArray movieArray = movieData.getJSONArray(movie_results);
String[] posterAddreess = new String[movieArray.length()];
//Fill ther posterAddreess with the URL to display
for(int j=0; j < movieArray.length(); j++){
String posterPath;
JSONObject movieArrayItem = movieArray.getJSONObject(j);
posterPath = movieArrayItem.getString(movie_poster);
posterAddreess[j] = "http://image.tmdb.org/t/p/w185/" + posterPath;
}
for (String s : posterAddreess) {
Log.v(LOG_TAG, "Thumbnail Links: " + s);
}
return posterAddreess;
}
#Override
protected String[] doInBackground(Void... params) {
HttpURLConnection urlConnection = null;
BufferedReader reader = null;
String JsonData = null;
String country = "US";
String rating = "R";
String sort = "popularity.desc";
String apiKey = "";
//building the URL for the movie DB
try {
//building the URL for the movie DB
final String MovieDatabaseUrl = "https://api.themoviedb.org/3/discover/movie?";
final String Country_for_release = "certification_country";
final String Rating = "certification";
final String Sorting_Order = "sort_by";
final String Api_Id = "api_key";
Uri buildUri = Uri.parse(MovieDatabaseUrl).buildUpon()
.appendQueryParameter(Country_for_release, country)
.appendQueryParameter(Rating, rating)
.appendQueryParameter(Sorting_Order, sort)
.appendQueryParameter(Api_Id, apiKey)
.build();
//Converting URI to URL
URL url = new URL(buildUri.toString());
Log.v(LOG_TAG, "Built URI = "+ buildUri.toString());
//Create the request to the Movie Database
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("GET");
urlConnection.connect();
//Read the input from the database into string
InputStream inputStream = urlConnection.getInputStream();
//StringBuffer for string Manipulation
StringBuffer buffer = new StringBuffer();
if (inputStream == null) {
// Nothing to do.
return null;
}
reader = new BufferedReader(new InputStreamReader(inputStream));
String line;
while ((line = reader.readLine()) != null) {
// Since it's JSON, adding a newline isn't necessary (it won't affect parsing)
// But it does make debugging a *lot* easier if you print out the completed
// buffer for debugging.
buffer.append(line + "\n");
}
if (buffer.length() == 0) {
// Stream was empty. No point in parsing.
return null;
}
JsonData = buffer.toString();
Log.v(LOG_TAG,"Forecaast Jason String" + JsonData );
} catch (IOException e) {
// If the code didn't successfully get the weather data, there's no point in attemping
// to parse it.
return null;
} finally {
if (urlConnection != null) {
urlConnection.disconnect();
}
if (reader != null) {
try {
reader.close();
} catch (final IOException e) {
Log.e(LOG_TAG, "Error closing stream", e);
}
}
try {
return extractdisplayFromJason(JsonData);
} catch (JSONException e) {
Log.e(LOG_TAG, e.getMessage(), e);
e.printStackTrace();
}
}
return null;
}
protected void onPostExecute(String[] posterAddreess) {
for (String poster : posterAddreess) {
display.addItem(poster);
}
}
}
}
This the ImageAdapter code
package com.example.popularmovis;
import android.content.Context;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import com.example.popularmovis.R;
import com.squareup.picasso.Picasso;
import java.util.ArrayList;
public class ImageAdapter extends BaseAdapter {
private Context mContext;
public ArrayList<String> images = new ArrayList<String>();
public ImageAdapter(Context c){
mContext = c;
}
#Override
public int getCount(){
return images.size();
}
#Override
public Object getItem(int position){
return images.get(position);
}
public long getItemId(int position){
return 0;
}
public View getView(int position, View convertView, ViewGroup parent){
ImageView imageview;
if (convertView == null){
imageview = new ImageView(mContext);
imageview.setPadding(0, 0, 0, 0);
//imageview.setLayoutParams(new GridLayout.MarginLayoutParams(ViewGroup.LayoutParams.FILL_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT));
imageview.setScaleType(ImageView.ScaleType.CENTER_INSIDE);
imageview.setAdjustViewBounds(true);
} else {
imageview = (ImageView) convertView;
}
Picasso.with(mContext).load(images.get(position)).placeholder(R.mipmap.ic_launcher).into(imageview);
return imageview;
}
/*
Custom methods
*/
public void addItem(String url){
images.add(url);
}
public void clearItems() {
images.clear();
}
}
When you use this in your onCreate method like this, it means that the object is local to the method and can't be use in other methods.
ImageAdapter display = new ImageAdapter(rootView.getContext());
First create a global class member variable
private ImageAdapter display;
then inside your onCreate method do this
display = new ImageAdapter(rootView.getContext());

Reading xml from rss feed

package com.example.nasadailyimage;
import android.app.Activity;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.widget.ImageView;
import android.widget.TextView;
public class NasaDailyImage extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_nasa_daily_image);
IotdHandler handler = new IotdHandler();
System.out.println("handler object created");
Log.d("NasaDailyImage","handler object created");
new ConfigParser().execute();//here i have called execute on my AsyncTaskclass
// handler.processFeed();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.nasa_daily_image, menu);
return true;
}
}
and my ConfigParser class
import java.io.InputStream;
import java.net.URL;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import org.xml.sax.InputSource;
import org.xml.sax.XMLReader;
import android.os.AsyncTask;
import android.util.Log;
public class ConfigParser extends AsyncTask<Void, Void,Void > {
private String url="http://www.nasa.gov/rss/dyn/image_of_the_day.rss";
#Override
protected Void doInBackground(Void... params) {
try {
SAXParserFactory factory = SAXParserFactory.newInstance();
SAXParser parser = factory.newSAXParser();
XMLReader reader = parser.getXMLReader();
IotdHandler handler=new IotdHandler();
reader.setContentHandler(handler);
InputStream inputStream = new URL(url).openStream();
reader.parse(new InputSource(inputStream));
}
catch (Exception e)
{
Log.d("IotdHandler", "Exception");
e.printStackTrace();
}
return null;
}
}
and my IotdHandler Class
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import org.xml.sax.Attributes;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.XMLReader;
import org.xml.sax.helpers.DefaultHandler;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.util.Log;
public class IotdHandler extends DefaultHandler {
private String url="http://www.nasa.gov/rss/dyn/image_of_the_day.rss";
private boolean inUrl = false;
private boolean inTitle = false;
private boolean inDescription = false;
private boolean inItem = false;
private boolean inDate = false;
private Bitmap image = null;
private String title = null;
private StringBuffer description = new StringBuffer();
private String date = null;
private String imageUrl;
private Bitmap getBitmap(String url) {
try {
HttpURLConnection connection = (HttpURLConnection)new URL(url).openConnection();
connection.setDoInput(true);
connection.connect();
InputStream input = connection.getInputStream();
Bitmap bitmap = BitmapFactory.decodeStream(input);
input.close();
return bitmap;
}
catch (IOException ioe)
{ ioe.printStackTrace(); }
return null;
}
public void startElement(String uri, String localName, String qName,Attributes attributes) throws SAXException {
if (localName.equals("enclosure"))
{ inUrl = true;
imageUrl=attributes.getValue("url");
System.out.println(imageUrl);
}
else { inUrl = false; }
if (localName.startsWith("item"))
{ inItem = true; }
else if (inItem) {
if (localName.equals("title"))
{ inTitle = true;
System.out.println("invtitle");}
else { inTitle = false; }
if (localName.equals("description"))
{ inDescription = true;
System.out.println("indiscription");}
else { inDescription = false; }
if (localName.equals("pubDate"))
{ inDate = true;
System.out.println("dtae");}
else { inDate = false; }
}
}
public void characters(char ch[], int start, int length) {
String chars = new String(ch).substring(start, start + length);
if (inUrl && url == null) { image = getBitmap(imageUrl); }
if (inTitle && title == null) { title = chars; }
if (inDescription) { description.append(chars); }
if (inDate && date == null) { date = chars; }
}
public Bitmap getImage() { return image; }
public String getTitle() { return title; }
public StringBuffer getDescription() { return description; }
public String getDate() { return date; }
}
So basically I want to get daily image updates from NASA, but in my program everything is returning null I don't know what I am trying wrong, my xml file is not parsing to avoid the NetworkOnMainTHread I have also used Async class, any help.
Here is the code parsing xml rss feed...
import java.net.URL;
import java.util.ArrayList;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.app.Activity;
import android.content.Context;
import android.os.Build;
import android.os.Bundle;
import android.os.StrictMode;
import android.text.Html;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ListView;
import android.widget.TextView;
#TargetApi(Build.VERSION_CODES.GINGERBREAD)
#SuppressLint("NewApi")
public class XMLParsingDOMExample extends Activity {
ArrayList<String> title;
ArrayList<String> description;
ArrayList<String> pubDate;
ItemAdapter adapter1;
#TargetApi(Build.VERSION_CODES.GINGERBREAD)
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
if (android.os.Build.VERSION.SDK_INT > 9) {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
}
ListView list = (ListView) findViewById(R.id.list);
title = new ArrayList<String>();
description = new ArrayList<String>();
pubDate = new ArrayList<String>();
parse();
adapter1 = new ItemAdapter(this);
list.setAdapter(adapter1);
}
protected void parse() {
// TODO Auto-generated method stub
try {
URL url = new URL(
"http://www.nasa.gov/rss/dyn/image_of_the_day.rss");
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document doc = db.parse(new InputSource(url.openStream()));
doc.getDocumentElement().normalize();
NodeList nodeList = doc.getElementsByTagName("item");
for (int i = 0; i < nodeList.getLength(); i++) {
Node node = nodeList.item(i);
Element fstElmnt = (Element) node;
NodeList nameList = fstElmnt.getElementsByTagName("title");
Element nameElement = (Element) nameList.item(0);
nameList = nameElement.getChildNodes();
title.add(((Node) nameList.item(0)).getNodeValue());
NodeList websiteList = fstElmnt.getElementsByTagName("description");
Element websiteElement = (Element) websiteList.item(0);
websiteList = websiteElement.getChildNodes();
description.add(((Node) websiteList.item(0)).getNodeValue());
NodeList websiteList1 = fstElmnt.getElementsByTagName("pubDate");
Element websiteElement1 = (Element) websiteList1.item(0);
websiteList1 = websiteElement1.getChildNodes();
pubDate.add(((Node) websiteList1.item(0)).getNodeValue());
}
} catch (Exception e) {
System.out.println("XML Pasing Excpetion = " + e);
}
}
class ItemAdapter extends BaseAdapter {
final LayoutInflater mInflater;
private class ViewHolder {
public TextView title_text;
public TextView des_text;
public TextView date_text;
}
public ItemAdapter(Context context) {
// TODO Auto-generated constructor stub
super();
mInflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
//#Override
public int getCount() {
return title.size();
}
//#Override
public Object getItem(int position) {
return position;
}
//#Override
public long getItemId(int position) {
return position;
}
//#Override
public View getView(final int position, View convertView, ViewGroup parent) {
View view = convertView;
final ViewHolder holder;
if (convertView == null) {
view = mInflater.inflate(R.layout.mainpage_listitem_activity, parent, false);
holder = new ViewHolder();
holder.title_text = (TextView) view.findViewById(R.id.title_text);
holder.des_text = (TextView) view.findViewById(R.id.des_text);
holder.date_text = (TextView) view.findViewById(R.id.date_text);
view.setTag(holder);
} else {
holder = (ViewHolder) view.getTag();
}
holder.title_text.setText(""+title.get(position));
holder.des_text.setText(""+Html.fromHtml(description.get(position)));
holder.date_text.setText(""+pubDate.get(position));
return view;
}
}
}
I posted a Gist on how to do this using the android-rss library with the droidQuery library:
final RSSHandler handler = new RSSHandler(new RSSConfig());
$.ajax(new AjaxOptions().url(options.url())
.type("GET")
.dataType("XML")
.context(this)
.SAXContentHandler(handler)
.success(new Function() {
#Override
public void invoke($ droidQuery, Object... params) {
RSSFeed feed = handler.feed();
//TODO: handle feed here.
}
}));
Make an interface in your project first
public interface mMyInterface {
void processFinish(String response);
}
Then in your AsyncTaskClass do the following modifications
public class ConfigParser extends AsyncTask<Void, Void,Void > {
public mMyInterface delegate=null;
private String url="http://www.nasa.gov/rss/dyn/image_of_the_day.rss";
#Override
protected Void doInBackground(Void... params) {
try {
//Log.i("inJSONPARSERCLASS","success");
DefaultHttpClient client=new DefaultHttpClient();
HttpPost post=new HttpPost(url);
HttpResponse httpResponse=client.execute(post);
HttpEntity entity=httpResponse.getEntity();
is=entity.getContent();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
catch (Exception e) {
Log.e("Connection Error", "Error " + e.toString());
}
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();
xml=sb.toString();
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
Log.i("main XML",""+xml);
return xml;
}
#Override
protected void onPostExecute(String result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
delegate.processFinish(result);
}
}
Now in your class which is extending the activity , implement the interface mMyInterface , this will override its method processFinish(String response), now use "response" as a string and pass it to the class where the parsing is being done
#Override
public void processFinish(String response) {
String xml=response;
//do SAXparsing stuff here, parse this xml string which contains the whole data u need to
parse
}
I hope this hint will work out for you very well. :)

FileNotFoundException while reading RSS in Android

I am trying to read an RSS feed. I have tried many links using the code below and succeeded, but when I try with that link above I get a FileNotFoundException. What could cause this, and how do I fix my code?
EfficientAdapter class:
package com.xmlparse;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.Drawable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
public class EfficientAdapter extends BaseAdapter
{
private Activity activity;
private ArrayList<Post> data;
private static LayoutInflater inflater = null;
//public ImageLoader imageLoader;
ViewHolder holder;
EfficientAdapter(Activity a, ArrayList<Post> d) {
activity = a;
data = d;
inflater = (LayoutInflater) activity
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
// imageLoader = new ImageLoader(activity.getApplicationContext());
}
#Override
public int getCount() {
return data.toArray().length;
}
#Override
public Object getItem(int position) {
return position;
}
#Override
public long getItemId(int position) {
return position;
}
public static class ViewHolder {
public TextView label;
public TextView addr;
public ImageView image;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View vi = convertView;
if (convertView == null) {
vi = inflater.inflate(R.layout.row, null);
holder = new ViewHolder();
holder.label = (TextView) vi.findViewById(R.id.title);
holder.addr = (TextView) vi.findViewById(R.id.details);
holder.image = (ImageView) vi.findViewById(R.id.thumb);
vi.setTag(holder);
} else
holder = (ViewHolder) vi.getTag();
holder.label.setText(data.get(position).getTitle());
// holder.addr.setText(data.get(position).getPubDate());
holder.addr.setText(data.get(position).getDescription());
imageLoader.DisplayImage((data.get(position).getThumbnail()), activity,
holder.image, 72, 72);
URL url = null;
try {
url = new URL((data.get(position).getThumbnail()));
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
InputStream content = null;
try {
content = (InputStream)url.getContent();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Drawable d = Drawable.createFromStream(content , "src");
Bitmap mIcon1 = null;
try {
mIcon1 =
BitmapFactory.decodeStream(url.openConnection().getInputStream());
} catch (IOException e) {
e.printStackTrace();
}
holder.image.setImageBitmap(Bitmap.createScaledBitmap(mIcon1, 72, 72, false));
return vi;
}
}
Post class:
package com.xmlparse;
public class Post {
private String title;
private String thumbnail;
private String url;
private String description;
private String pubDate;
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getThumbnail() {
return thumbnail;
}
public void setThumbnail(String thumbnail) {
this.thumbnail = thumbnail;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public void setDescription(String description) {
this.description = description;
}
public String getDescription() {
return description;
}
public void setPubDate(String pubDate) {
this.pubDate = pubDate;
}
public String getPubDate() {
return pubDate;
}
}
xmlparsemain activity class:
package com.xmlparse;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.HashMap;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import org.xml.sax.Attributes;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.XMLReader;
import org.xml.sax.helpers.DefaultHandler;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
public class xmlparsemain extends Activity {
/** Called when the activity is first created. */
ListView lv1;
ProgressDialog ShowProgress;
public ArrayList<Post> PostList = new ArrayList<Post>();
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
lv1 = (ListView) findViewById(R.id.listView1);
ShowProgress = ProgressDialog.show(xmlparsemain.this, "",
"Loading. Please wait...", true);
new loadingTask().execute("http://screenrant.com/mobile/movie-reviews-feed.php");
lv1.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
Intent intent = new Intent(Intent.ACTION_VIEW).setData(Uri
.parse(PostList.get(position).getUrl()));
startActivity(intent);
}
});
}
class loadingTask extends AsyncTask<String, Void, String> {
protected String doInBackground(String... urls) {
SAXHelper sh = null;
try {
sh = new SAXHelper(urls[0]);
} catch (MalformedURLException e) {
e.printStackTrace();
}
sh.parseContent("");
return "";
}
protected void onPostExecute(String s) {
lv1.setAdapter(new EfficientAdapter(xmlparsemain.this, PostList));
ShowProgress.dismiss();
}
}
class SAXHelper {
public HashMap<String, String> userList = new HashMap<String, String>();
private URL url2;
public SAXHelper(String url1) throws MalformedURLException {
this.url2 = new URL(url1);
}
public RSSHandler parseContent(String parseContent) {
RSSHandler df = new RSSHandler();
try {
SAXParserFactory spf = SAXParserFactory.newInstance();
SAXParser sp = spf.newSAXParser();
XMLReader xr = sp.getXMLReader();
xr.setContentHandler(df);
/* URLConnection con = url2.openConnection();
con.setConnectTimeout(20000);
InputSource is = new InputSource(new InputStreamReader(con.getInputStream()));
xr.parse(is);*/
xr.parse(new InputSource(url2.openStream()));
} catch (Exception e) {
e.printStackTrace();
}
return df;
}
}
class RSSHandler extends DefaultHandler {
private Post currentPost = new Post();
StringBuffer chars = new StringBuffer();
#Override
public void startElement(String uri, String localName, String qName,
Attributes atts) {
chars = new StringBuffer();
if (localName.equalsIgnoreCase("item")) {
}
}
#Override
public void endElement(String uri, String localName, String qName)
throws SAXException {
if (localName.equalsIgnoreCase("title")
&& currentPost.getTitle() == null) {
currentPost.setTitle(chars.toString());
}
if (localName.equalsIgnoreCase("pubDate")
&& currentPost.getPubDate() == null) {
currentPost.setPubDate(chars.toString());
}
if (localName.equalsIgnoreCase("description")
&& currentPost.getDescription() == null) {
currentPost.setDescription(chars.toString());
}
if (localName.equalsIgnoreCase("thumbnail")
&& currentPost.getThumbnail() == null) {
currentPost.setThumbnail(chars.toString());
}
if (localName.equalsIgnoreCase("link")
&& currentPost.getUrl() == null) {
currentPost.setUrl(chars.toString());
}
if (localName.equalsIgnoreCase("item")) {
PostList.add(currentPost);
currentPost = new Post();
}
}
#Override
public void characters(char ch[], int start, int length) {
chars.append(new String(ch, start, length));
}
}
}
My logcat report:
02-29 15:20:44.183: W/System.err(2470): java.io.FileNotFoundException: http://screenrant.com/mobile/movie-news-feed.php
try using HTtpConnection instead of URLConnection, as follows:
InputStream callWebErvice(String serviceURL){
// http get client
HttpClient client=new DefaultHttpClient();
HttpGet getRequest=new HttpGet();
try {
// construct a URI object
getRequest.setURI(new URI(serviceURL));
} catch (URISyntaxException e) {
Log.e("URISyntaxException", e.toString());
}
// buffer reader to read the response
BufferedReader in=null;
// the service response
HttpResponse response=null;
try {
// execute the request
response = client.execute(getRequest);
} catch (ClientProtocolException e) {
Log.e("ClientProtocolException", e.toString());
} catch (IOException e) {
Log.e("IO exception", e.toString());
}
if(response!=null)
return response.getEntity().getContent();
else
return null;
}
and change line xr.parse(new InputSource(url2.openStream()));
to
xr.parse(new InputSource(callWebErvice(url2)));

Categories

Resources