Save data received from the site parse.com on the device - android

How can I save the data coming from parse.com within the android device?
I'm trying to save the data somewhere in the application for when you have no network, the customer can still get the data saved on the device.
I am using this code to make the list and is working, just missing the issue of saving data when you have no internet.
package com.example.ronysueliton.patospizzas;
import android.app.ActionBar;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.view.Menu;
/**
* Created by Rony Sueliton on 11/04/2015.
*/
import java.util.ArrayList;
import java.util.List;
import android.app.Activity;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.TextView;
import com.parse.FindCallback;
import com.parse.GetCallback;
import com.parse.ParseException;
import com.parse.ParseObject;
import com.parse.ParseQuery;
public class Pizzarias extends ActionBarActivity {
// Declare Variables
Boolean bColorStatus = true;
TextView status;
ListView listview;
List<ParseObject> ob;
ProgressDialog mProgressDialog;
ListViewAdapterPizzarias adapter;
private List<WorldPopulation> worldpopulationlist = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_pizzarias);
new RemoteDataTask().execute();
}
#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_pizzarias, menu);
//Os metodos abaixo são para mostrar o icone do aplicativo na action bar
getSupportActionBar().setDisplayShowHomeEnabled(true);
getSupportActionBar().setLogo(R.drawable.ic_launcher);
getSupportActionBar().setDisplayUseLogoEnabled(true);
return true;
}
/*#Override
public boolean onOptionsItemSelected(MenuItem item) {
onBackPressed();
return true;
}*/
//RemoteDataTask AsyncTask
private class RemoteDataTask extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Create a progressdialog
mProgressDialog = new ProgressDialog(Pizzarias.this);
// Set progressdialog title
mProgressDialog.setTitle("Carregando Pizzarias");
// Set progressdialog message
mProgressDialog.setMessage("Aguarde...");
mProgressDialog.setIndeterminate(false);
// Show progressdialog
mProgressDialog.show();
}
#Override
protected Void doInBackground(Void... params) {
// Create the array
worldpopulationlist = new ArrayList<WorldPopulation>();
try {
// Locate the class table named "Country" in Parse.com
ParseQuery query = new ParseQuery("GerenciarPizzariasPatos");
// Locate the column named "ranknum" in Parse.com and order list
// by ascending,
query.orderByAscending("nome");
ob = query.find();
for (ParseObject country : ob) {
WorldPopulation map = new WorldPopulation();
map.setNome((String) country.get("nome"));
map.setEndereco((String) country.get("endereco"));
map.setTelefone((String) country.get("telefone"));
map.setStatus((String) country.get("status"));
worldpopulationlist.add(map);
}
} catch (ParseException e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void result) {
// Locate the listview in listview_main.xml
listview = (ListView) findViewById(R.id.listviewpizzarias);
// Pass the results into ListViewAdapter.java
adapter = new ListViewAdapterPizzarias(Pizzarias.this,
worldpopulationlist);
// Binds the Adapter to the ListView
listview.setAdapter(adapter);
// Close the progressdialog
mProgressDialog.dismiss();
}
}
}
////
public class ParseApplication extends Application {
#Override
public void onCreate() {
super.onCreate();
Parse.enableLocalDatastore(this);
// Add your initialization code here
Parse.initialize(this, "xxx", "xxx");
ParseUser.enableAutomaticUser();
ParseACL defaultACL = new ParseACL();
// If you would like all objects to be private by default, remove this
// line.
defaultACL.setPublicReadAccess(true);
ParseACL.setDefaultACL(defaultACL, true);
}
}

Just add pin(map); after worldpopulationlist.add(map); and add to logic that will check whether connection is available and would enable query.fromLocalDatastore() option in case of unavailable connection before executing query

I changed my line of code to this, I tried to use a tutorial of internet parse.com blog, but is giving an error GET, underlined with a red line.
I tried to use an example of the site: http://blog.parse.com/announcements/take-your-app-offline-with-parse-local-datastore/
#Override
protected Void doInBackground(Void... params) {
// Create the array
worldpopulationlist = new ArrayList<WorldPopulation>();
try {
// Locate the class table named "Country" in Parse.com
//ParseQuery query = new ParseQuery("GerenciarPizzariasPatos");
String objectId = "GFiBnjCE4v";
ParseObject feed = ParseQuery.get(objectId); // error GET // Online ParseQuery result
feed.fetch();
feed.put("fechado", true);
feed.saveEventually();
//ParseQuery<ParseObject> query = ParseQuery.getQuery("GerenciarPizzariasPatos");
ParseQuery<ParseObject> query = ParseQuery.get("GerenciarPizzariasPatos") // error GET
.fromLocalDatastore()
.whereEquals("fechado", true)
.findInBackground(new FindCallback<ParseObject>() {
public void done(List<ParseObject> objects, ParseException e) {
// "feed" ParseObject will be returned in the list of results
}
});
// Locate the column named "ranknum" in Parse.com and order list
// by ascending,
query.orderByAscending("nome");
ob = query.find();
for (ParseObject country : ob) {
WorldPopulation map = new WorldPopulation();
map.setNome((String) country.get("nome"));
map.setEndereco((String) country.get("endereco"));
map.setTelefone((String) country.get("telefone"));
map.setStatus((String) country.get("status"));
worldpopulationlist.add(map);
}
} catch (ParseException e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
return null;
}

Related

ArrayList get method causes app to be crashed

I am inflating the menu from JSON which contain its name and id. I had written Fragment5 which is used to be calling an URL for JSON. In that url I want to call the id of the menu.
This is my code. The code is running fine if I am commenting the two line
String scat = menu_nms.get(0);
int cat = Integer.parseInt(scat);
MainActivity.java
package com.latrodealz.wowwdealz;
import android.app.Fragment;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.app.ProgressDialog;
import android.app.SearchManager;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.SearchView;
import android.widget.Toast;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonArrayRequest;
import com.android.volley.toolbox.Volley;
import com.google.android.gms.appindexing.Action;
import com.google.android.gms.appindexing.AppIndex;
import com.google.android.gms.common.api.GoogleApiClient;
import com.latrodealz.wowwdealz.adapter.SlidingMenuAdapter;
import com.latrodealz.wowwdealz.fragment.Fragment1;
import com.latrodealz.wowwdealz.fragment.Fragment2;
import com.latrodealz.wowwdealz.fragment.Fragment3;
import com.latrodealz.wowwdealz.fragment.Fragment4;
import com.latrodealz.wowwdealz.fragment.Fragment5;
import com.latrodealz.wowwdealz.model.ItemSlideMenu;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.List;
/**
* Created by NgocTri on 10/18/2015.
*/
public class MainActivity extends AppCompatActivity {
private List<ItemSlideMenu> listSliding;
private SlidingMenuAdapter adapter;
private ListView listViewSliding;
private DrawerLayout drawerLayout;
private ActionBarDrawerToggle actionBarDrawerToggle;
//Web api url
public static final String MENU_URL = "http://69.89.31.191/~webtech6/android_wow/menu_dtls.php";
//Tag values to read from json
public static final String MENU_ID = "menu_id";
public static final String MENU_NM = "menu_nm";
//ArrayList for Storing menu ids and names
private ArrayList<String> menu_ids;
private ArrayList<String> menu_nms;
/**
* ATTENTION: This was auto-generated to implement the App Indexing API.
* See https://g.co/AppIndexing/AndroidStudio for more information.
*/
private GoogleApiClient client;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
menu_ids = new ArrayList<>();
menu_nms = new ArrayList<>();
//Calling the getMenuData method
getMenuData();
//Init component
listViewSliding = (ListView) findViewById(R.id.lv_sliding_menu);
drawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
listSliding = new ArrayList<>();
//Add item for sliding list
listSliding.add(new ItemSlideMenu(R.drawable.ic_action_settings, "Home"));
adapter = new SlidingMenuAdapter(this, listSliding);
listViewSliding.setAdapter(adapter);
//Display icon to open/ close sliding list
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
//Set title
setTitle(listSliding.get(0).getTitle());
//item selected
listViewSliding.setItemChecked(0, true);
//Close menu
drawerLayout.closeDrawer(listViewSliding);
//Display fragment 1 when start
replaceFragment(0);
//Handle on item click
listViewSliding.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
//Set title
setTitle(listSliding.get(position).getTitle());
//item selected
listViewSliding.setItemChecked(position, true);
//Replace fragment
replaceFragment(position);
//Close menu
drawerLayout.closeDrawer(listViewSliding);
}
});
actionBarDrawerToggle = new ActionBarDrawerToggle(this, drawerLayout, R.string.drawer_opened, R.string.drawer_closed) {
#Override
public void onDrawerOpened(View drawerView) {
super.onDrawerOpened(drawerView);
invalidateOptionsMenu();
}
#Override
public void onDrawerClosed(View drawerView) {
super.onDrawerClosed(drawerView);
invalidateOptionsMenu();
}
};
drawerLayout.addDrawerListener(actionBarDrawerToggle);
// ATTENTION: This was auto-generated to implement the App Indexing API.
// See https://g.co/AppIndexing/AndroidStudio for more information.
client = new GoogleApiClient.Builder(this).addApi(AppIndex.API).build();
}
private void getMenuData() {
//Showing a progress dialog while our app fetches the data from url
final ProgressDialog loading = ProgressDialog.show(this, "Please wait...", "Fetching data...", false, false);
//Creating a json array request to get the json from our api
JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(MENU_URL,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
//Dismissing the progressdialog on response
loading.dismiss();
//Displaying our grid
showMenu(response);
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
}
);
//Creating a request queue
RequestQueue requestQueue = Volley.newRequestQueue(this);
//Adding our request to the queue
requestQueue.add(jsonArrayRequest);
}
private void showMenu(JSONArray jsonArray) {
//Looping through all the elements of json array
for (int i = 0; i < jsonArray.length(); i++) {
//Creating a json object of the current index
JSONObject obj = null;
try {
//getting json object from current index
obj = jsonArray.getJSONObject(i);
//getting menuid and menuname from json object
menu_ids.add(obj.getString(MENU_ID));
menu_nms.add(obj.getString(MENU_NM));
} catch (JSONException e) {
e.printStackTrace();
}
}
//Add item for sliding list
for (int i = 0; i < menu_ids.size(); i++) {
listSliding.add(new ItemSlideMenu(R.drawable.ic_action_about, menu_nms.get(i)));
}
adapter = new SlidingMenuAdapter(this, listSliding);
listViewSliding.setAdapter(adapter);
//Add item for sliding list
listSliding.add(new ItemSlideMenu(R.drawable.ic_action_settings, "MY CART"));
listSliding.add(new ItemSlideMenu(R.drawable.ic_action_settings, "MY ACCOUNT"));
listSliding.add(new ItemSlideMenu(R.drawable.ic_action_settings, "MY ORDERS"));
adapter = new SlidingMenuAdapter(this, listSliding);
listViewSliding.setAdapter(adapter);
//Display Array List
// Toast.makeText(getBaseContext(), menu_ids + "", Toast.LENGTH_LONG).show();
// Toast.makeText(getBaseContext(), menu_nms + "", Toast.LENGTH_LONG).show();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main_menu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (actionBarDrawerToggle.onOptionsItemSelected(item)) {
return true;
}
switch (item.getItemId()) {
case R.id.action_search:
// User chose the "Settings" item, show the app settings UI...
Intent intent = new Intent(MainActivity.this, SearchableActivity.class);
startActivityForResult(intent, 0);
//Toast.makeText(this, "You have selected Search Search Menu", Toast.LENGTH_SHORT).show();
return true;
case R.id.action_kart:
// User chose the "Favorite" action, mark the current item
// as a favorite...
Toast.makeText(this, "You have selected Search KART Menu", Toast.LENGTH_SHORT).show();
return true;
case R.id.action_notifications:
// User chose the "Favorite" action, mark the current item
// as a favorite...
Toast.makeText(this, "You have selected Search Notifications Menu", Toast.LENGTH_SHORT).show();
return true;
default:
// If we got here, the user's action was not recognized.
// Invoke the superclass to handle it.
return super.onOptionsItemSelected(item);
}
//return super.onOptionsItemSelected(item);
}
#Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
actionBarDrawerToggle.syncState();
}
/**
* Called when the user clicks the Search Menu
* public void callSearchActivity(View view) {
* Intent intent = new Intent(this, SearchActivity.class);
* startActivity(intent);
* }
*/
//Create method replace fragment
private void replaceFragment(int pos) {
Fragment fragment = null;
int menu_size = menu_ids.size();
String scat = menu_nms.get(0);
int cat = Integer.parseInt(scat);
if (pos == 0) {
fragment = new Fragment1();
} else if (pos > 0 && pos <= menu_size) {
SharedPreferences sharePref = getSharedPreferences("menu_dtls", Context.MODE_PRIVATE);
sharePref.edit().remove("menu_id").commit();
SharedPreferences.Editor editor = sharePref.edit();
editor.putInt("menu_id", pos);
editor.apply();
fragment = new Fragment5();
} else if (pos == (menu_size + 1)) {
fragment = new Fragment2();
} else if (pos == (menu_size + 2)) {
fragment = new Fragment3();
} else if (pos == (menu_size + 3)) {
fragment = new Fragment4();
} else {
fragment = new Fragment1();
}
if (null != fragment) {
FragmentManager fragmentManager = getFragmentManager();
FragmentTransaction transaction = fragmentManager.beginTransaction();
transaction.replace(R.id.main_content, fragment);
transaction.addToBackStack(null);
transaction.commit();
}
}
#Override
public void onStart() {
super.onStart();
// ATTENTION: This was auto-generated to implement the App Indexing API.
// See https://g.co/AppIndexing/AndroidStudio for more information.
client.connect();
Action viewAction = Action.newAction(
Action.TYPE_VIEW, // TODO: choose an action type.
"Main Page", // TODO: Define a title for the content shown.
// TODO: If you have web page content that matches this app activity's content,
// make sure this auto-generated web page URL is correct.
// Otherwise, set the URL to null.
Uri.parse("http://host/path"),
// TODO: Make sure this auto-generated app deep link URI is correct.
Uri.parse("android-app://com.latrodealz.wowwdealz/http/host/path")
);
AppIndex.AppIndexApi.start(client, viewAction);
}
#Override
public void onStop() {
super.onStop();
// ATTENTION: This was auto-generated to implement the App Indexing API.
// See https://g.co/AppIndexing/AndroidStudio for more information.
Action viewAction = Action.newAction(
Action.TYPE_VIEW, // TODO: choose an action type.
"Main Page", // TODO: Define a title for the content shown.
// TODO: If you have web page content that matches this app activity's content,
// make sure this auto-generated web page URL is correct.
// Otherwise, set the URL to null.
Uri.parse("http://host/path"),
// TODO: Make sure this auto-generated app deep link URI is correct.
Uri.parse("android-app://com.latrodealz.wowwdealz/http/host/path")
);
AppIndex.AppIndexApi.end(client, viewAction);
client.disconnect();
}
}
Fragment5.java
package com.latrodealz.wowwdealz.fragment;
import android.app.Fragment;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.ListView;
import com.latrodealz.wowwdealz.R;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.HashMap;
public class Fragment5 extends Fragment {
JSONObject jsonobject;
JSONArray jsonarray;
ListView listview;
ListViewAdapter adapter;
ProgressDialog mProgressDialog;
ArrayList<HashMap<String, String>> arraylist;
static String RANK = "rank";
static String COUNTRY = "country";
static String POPULATION = "population";
static String FLAG = "flag";
public Fragment5() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment5, container, false);
//TextView menu_id = (TextView)rootView.findViewById(R.id.textid);
//SharedPreferences sharePref = this.getActivity().getSharedPreferences("menu_dtls", Context.MODE_PRIVATE);
//int menuId = sharePref.getInt("menu_id", 0);
// menu_id.setText(String.valueOf(menuId));
ImageView purple=(ImageView)rootView.findViewById(R.id.gridicon);
purple.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
getFragmentManager()
.beginTransaction()
.replace(R.id.main_content, new Fragment4())
.commit();
}
});
new DownloadJSON().execute();
return rootView;
}
// DownloadJSON AsyncTask
private class DownloadJSON extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Create a progressdialog
mProgressDialog = new ProgressDialog(getActivity());
// Set progressdialog title
mProgressDialog.setTitle("Fetching data...");
// Set progressdialog message
mProgressDialog.setMessage("Loading...");
mProgressDialog.setIndeterminate(false);
// Show progressdialog
mProgressDialog.show();
}
#Override
protected Void doInBackground(Void... params) {
// Create an array
SharedPreferences sharePref = getActivity().getSharedPreferences("menu_dtls", Context.MODE_PRIVATE);
int menuId = sharePref.getInt("menu_id", 0);
arraylist = new ArrayList<HashMap<String, String>>();
// Retrieve JSON Objects from the given URL address
jsonobject = JSONfunctions
.getJSONfromURL("http://69.89.31.191/~webtech6/android_wow/load.php?catId="+menuId);
try {
// Locate the array name in JSON
jsonarray = jsonobject.getJSONArray("worldpopulation");
for (int i = 0; i < jsonarray.length(); i++) {
HashMap<String, String> map = new HashMap<String, String>();
jsonobject = jsonarray.getJSONObject(i);
// Retrive JSON Objects
map.put("rank", jsonobject.getString("rank"));
map.put("country", jsonobject.getString("country"));
map.put("population", jsonobject.getString("population"));
map.put("flag", jsonobject.getString("flag"));
// Set the JSON Objects into the array
//Toast.makeText(getActivity().getBaseContext(), map + "", Toast.LENGTH_LONG).show();
arraylist.add(map);
}
} catch (JSONException e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void args) {
// Locate the listview in listview_main.xml
listview = (ListView) getActivity().findViewById(R.id.listview);
// Pass the results into ListViewAdapter.java
adapter = new ListViewAdapter(getActivity(), arraylist);
// Set the adapter to the ListView
listview.setAdapter(adapter);
// Close the progressdialog
mProgressDialog.dismiss();
}
}
}
Perhaps you get exception during JSON parsing. You may surround Integer.parseInt(scat); with try- catch catching ParsingException if Json has no such a field.
But more neat solution is to use GSON with Retrofit, so you can automatically parse you response to java objects, created by jsonschema2pojo.com

display listview of files available on any files hosting server in app

i am working on android app which will show the files available on any file hosting service in a listview so that I can download them. I am okay with any file hosting service if that works for me. I have tried dropbox but not working for me.please suggest me the code or anything which is regarding this topic. I have even tried the Apache service but didn't work.
thank you!!!
package com.example.mangesh.comp;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.view.Menu;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.List;
public class ass_bce extends ActionBarActivity {
DLFiles clientServerInterface = new DLFiles();
private String localjsonString="{\"data\":[{\"file_name\": \"file.pdf\", \"physical_path\": \"/pic/file.png\"}]";
private ListView listView;
private List list;
#Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_ass_bce);
listView = (ListView) findViewById(R.id.listView1);
new RetreiveData().execute();
}
#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_ass_bce, menu);
return true;
}
class RetreiveData extends AsyncTask<String,Void,List<String>> {
#Override
protected List<String> doInBackground(String... strings) {
// TODO Auto-generated method stub
try{
JSONObject jobj = clientServerInterface.makeHttpRequest("localhost/man.php");
JSONArray jsonArray = new JSONArray(localjsonString);
list = new ArrayList<String>();
if (jsonArray != null)
{
int len = jsonArray.length();
for (int i=0;i<len;i++)
{
list.add(jsonArray.get(i).toString());
}
}
else
Toast.makeText(getApplicationContext(),"Array is Null",Toast.LENGTH_LONG).show();
} catch (JSONException e) {
Toast.makeText(getApplicationContext(),"Error"+e.toString(),Toast.LENGTH_LONG).show();
}
return list;
}
protected void onPostExecute(List<String> list) {
ArrayAdapter<String> aa = new ArrayAdapter<String>(getApplicationContext(), android.R.layout.simple_list_item_1, list);
listView.setAdapter(aa);
}
}
}
You can make a simple API which will take request from the Android app and return a response in JSON containing the files and their path.
For example,
PHP Snippet,
if (isset($_POST['tag']) && $_POST['tag'] != '') {
// get tag
$tag = $_POST['tag'];
// check for tag type
if ($tag == 'get_data') {
// print the data
$user = $db->getData();
$response["error"] = FALSE;
$response["data"]["file_name"] = $user["file_name"];
$response["data"]["physical_path"] = $user["physical_path"];
echo json_encode($response);
}
}
at http://anyhost.com/API/api.php accepts a POST request and responses with the following JSON,
{
"data": [
{
"file_name": "file.png",
"physical_path": "/pic/file.png"
},
{
"file_name": "file.png",
"physical_path": "/pic/file.png"
}
]
}
Now simply parse this JSON and show it in your app. See the example here,
Android Populating a ListView from JSON

I used Jsoup to get and using AsyncTask , ArrayList<String> and displayed on ListView and

package com.example.yannews;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import android.os.AsyncTask;
import android.os.Bundle;
import android.app.Activity;
import android.app.ProgressDialog;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
public class MainActivity extends Activity {
// URL Address
String url = "http://www.yan.vn/";
ProgressDialog mProgressDialog;
ListView listview;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listview = (ListView)findViewById(R.id.listView1);
// Locate the Buttons in activity_main.xml
Button titlebutton = (Button) findViewById(R.id.titlebutton);
Button descbutton = (Button) findViewById(R.id.descbutton);
// Capture button click
titlebutton.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
// Execute Title AsyncTask
new Title().execute();
}
});
// Capture button click
descbutton.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
// Execute Description AsyncTask
new Description().execute();
}
});
}
// Title AsyncTask
private class Title extends AsyncTask<Void, Void, Void> {
String title;
#Override
protected void onPreExecute() {
super.onPreExecute();
mProgressDialog = new ProgressDialog(MainActivity.this);
mProgressDialog.setTitle("Android Basic JSoup Tutorial");
mProgressDialog.setMessage("Loading...");
mProgressDialog.setIndeterminate(false);
mProgressDialog.show();
}
#Override
protected Void doInBackground(Void... params) {
try {
// Connect to the web site
Document document = Jsoup.connect(url).get();
// Get the html document title
title = document.title();
System.out.println(title);
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
//Title get works however,displaying the bunch of information is not working with me.
#Override
protected void onPostExecute(Void result) {
// Set title into TextView
TextView txttitle = (TextView) findViewById(R.id.titletxt);
txttitle.setText(title);
mProgressDialog.dismiss();
}
}
// Description AsyncTask
private class Description extends AsyncTask<Void, Void, ArrayList<String>> {
ArrayList<String> news = new ArrayList<String>();
#Override
protected void onPreExecute() {
super.onPreExecute();
mProgressDialog = new ProgressDialog(MainActivity.this);
mProgressDialog.setTitle("Android Basic JSoup Tutorial");
mProgressDialog.setMessage("Loading...");
mProgressDialog.setIndeterminate(false);
mProgressDialog.show();
}
The problem is in doInBackGround , the code didn't get information but when I tested on Java project , it completely worked.
#Override
protected ArrayList<String> doInBackground(Void... params)
{
//String desc = "Những ngôi sao trẻ \"giỏi kiếm tiền\" nhất Hollywood";
Document document = null;
try {
document = Jsoup.connect(url).get();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
for(Element e : document.select("div[class=dvSubBannerText dvTitle15]"))
{
news.add(e.text());
}
//getString(news);
return news;
}
When debugging, I realized that news didn't contains any information.
#Override
protected void onPostExecute( ArrayList<String> result) {
// Set description into TextView
ArrayAdapter<String>adapter = new ArrayAdapter<String>(MainActivity.this,android.R.layout.simple_list_item_1,android.R.id.text1);
for (String temp_result : result) {
adapter.add(temp_result);
}
listview.setAdapter(adapter);
mProgressDialog.dismiss();
}
}
// Logo AsyncTask
}
So the question is why I can't display the information I got from website by Jsoup to ListView ?
Anyone can help me with that . I really appreciate.

Android: Jsoup: GET put all items on ListView

If doc isn't null i want to put all data from doc to ListView, how do it?
If to write Element = doc.select("someSelector"); then i can't to put it in ListView;
Sorry for my english(i'am Russian)
Code:
package com.example.phpfunctions;
import java.io.IOException;
import java.util.Locale;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.select.Elements;
import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.Menu;
import android.widget.AutoCompleteTextView;
import android.widget.ListView;
import android.widget.Toast;
public class MainActivity extends Activity {
private final String lang = Locale.getDefault().getLanguage();
private final String functions_list = "someURL";
private final ListView lv = (ListView) findViewById(R.id.listView1);
Document doc = null;
AutoCompleteTextView input;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
new getData().execute(functions_list);
if(doc != null)
{
//--Write code here--//
}
else
Toast.makeText(this, "error", Toast.LENGTH_LONG).show();
}
#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;
}
class getData extends AsyncTask<String, Void, Document> {
protected Document doInBackground(String... urls) {
try {
Document data = Jsoup.connect(urls[0]).get();
return data;
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return null;
}
}
protected void onPreExecute() {
}
protected void onPostExecute(Document result) {
doc = result;
}
}
}
You can select all of the Elements from a page if you use the * as a wildcard character when calling doc.select(). To add all of the elements to a ListView you need to save each element into some type of array, e.g. an ArrayList and also use an ArrayAdapter.
For example:
ArrayList<String> htmlElements = new ArrayList<String>();
if(doc != null)
{
//--Write code here--//
Elements elements = doc.select("*"); // select all elements from that page
for (Element e : elements) {
htmlElements.add(e.html()); // or e.text(), depends on what you require
}
ArrayAdapter<String> adapter = new ArrayAdapter<String>(MainActivity.this, android.R.layout.simple_list_item_1, htmlElements);
lv.setAdapter(adapter);
}
If you only want to list the elements from the body of the document, call doc.body().select("*") instead. The documentation is worth a read for some other tricks.

Jsoup parsing with Android

I'm trying to parse html with Jsoup lib. However, I did not get what I want.
I want to bring to the screen of a mobile device the entire text of the tag <pre>
Please tell me, how do I get the text from web? How do I need to fix?
Web site: http://devanswers.ru/text.php
package com.example.devanswers;
import java.io.IOException;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageView;
import android.widget.TextView;
public class MainActivity extends Activity {
TextView DevMainText;
ImageView DevMainImage;
MyTask DevMain;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
DevMainText = (TextView) findViewById(R.id.DevMainText);
DevMainImage = (ImageView) findViewById(R.id.DevMainImage);
OnClickListener onClick = new OnClickListener() {
public void onClick(View v) {
DevMain = new MyTask();
DevMain.execute();
}
};
DevMainImage.setOnClickListener(onClick);
}
#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;
}
class MyTask extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
DevMainImage.setEnabled(false);
}
#Override
protected Void doInBackground(Void... params) {
Document doc;
try {
doc = Jsoup.connect("http://devanswers.ru/text.php").get();
Elements links = doc.getElementsByTag("pre");
for (Element link : links) {
DevMainText.setText((link.text()));
}
} catch (IOException e) {
// TODO Auto-generated catch block
DevMainText.setText("Error");
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
DevMainImage.setEnabled(true);
}
}
}
I have never use the Jsoup before but what i can see from your code that you over write what in the DevMainText each time you get data from the page
so you should setText in your textview like this:
String maintext = "";
for (Element link : links) {
maintext += link.text() +"\n";
}
DevMainText.setText(maintext);
Infact the response is not wrapped in the <pre> tag. Its the browser who wraps the raw response in the <pre> tag when you view the source.
Instead of doc.getElementsByTag("pre") try doc.getElementsByTag("body")
You could also try using the Android WebView component, if you want to display the entire page.
http://developer.android.com/reference/android/webkit/WebView.html
You can easily parse the page using the URI class Uri uri = Uri.parse("http://devanswers.ru/text.php");and then display this in a WebView.

Categories

Resources