I have been referring this app to make a gallery module
https://github.com/nostra13/Android-Universal-Image-Loader
However according to the requirement in my app the images are dynamically added.So, I am fetching all the images via JSON.The image response from JSON Iam adding in the arraylist.
How should I pass "image_urls.add(folio.getString(i));" in the new class :
public class Test extends Activity{
private static String url = "http://www.xyz.com/album_pro/array_to_encode";
JSONArray folio = null;
ArrayList<String> urlList = new ArrayList<String>();
#SuppressLint("NewApi")
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
JSONParser jParser = new JSONParser();
{
try{
JSONObject json = jParser.getJSONFromUrl(url);
Log.v("URL",json.toString());
JSONObject seo = json.getJSONObject("SEO");
Log.v("seo",seo.toString());
JSONArray folio = seo.getJSONArray("Folio");
ArrayList<String> image_urls = new ArrayList<String>();
for(int i=0;i< folio.length();i++)
{
image_urls.add(folio.getString(i));
}
}
catch(Exception e)
{
e.printStackTrace();
}
}
}
}
How should I pass "image_urls.add(folio.getString(i));" in a non activity class named "Images"
i.e
public class Images {
public final static String[] imageUrls = new String[] {
**Required the arraylist of "Test" activity**
};
public final static String[] imageThumbUrls = new String[] {
**Required the arraylist of "Test" activity**
};
}
Make the ArrayList public and static and use it in other class as Test.urlList
Make the Images members non-final so that you can set them at runtime.
After your loop which add image urls to image_urls ArrayList, set the properties of Images class:
Images.imageUrls = image_urls.toArray();
Simple way is to make the image_urls as public static. since it contains only urls right? only small amount of data and in the Image class access that with
Test.image_urls.get(integer);
Related
I want to put data from a MySQL database table into Android Studio.
For modifying script from tutorial.
In tutorial ArrayList value is:
HomeCollection.date_collection_arr = new ArrayList<HomeCollection>();
HomeCollection.date_collection_arr.add(new HomeCollection("2018-07-08" ,"Title1","Subject1","Description1"));
HomeCollection.date_collection_arr.add(new HomeCollection("2018-07-09" ,"Title2","Subject2","Description2"));
HomeCollection.date_collection_arr.add(new HomeCollection("2018-07-10" ,"Title3","Subject3","Description3"));
My Question:
How to modify data Array, in example with all data in MySql table
having below columns?
| id | date | title | subject | description |
Any help will be greatly appreciated
//you can do like this.
get the value from arraylist into string array then split the array and then send the string to database.given below code
String[] value = HomeCollection.date_collection_arr.get(0).split(",");
String date=value[0];
String title=value[1];
String description=value[2];
//if your array list value contain space use below code
String[] valuetrim= HomeCollection.date_collection_arr.get(0).split("\\s*,\\s*");
String valuetrim=value[0];
String valuetrim=value[1];
String valuetrim=value[2];
Thanx for your clue, but I still not understand,
I try to get array list, from this way n success to views data at list (bellow array scrip),
maybe someone can give me more specific, how to implement/combine value data i have got from this way (below) to array at my question (i want to impemented sample script from this link https://www.developerbrothers.com/highlight-events-custom-calendar-android-studio-developerbrothers-com/) but i want data values get from MySql, Thanks
private void showOrder(){
JSONObject jsonObject = null;
ArrayList> list = new ArrayList>();
try {
jsonObject = new JSONObject(JSON_STRING);
JSONArray result = jsonObject.getJSONArray(konfigurasi.TAG_JSON_ARRAY);
for(int i = 0; i<result.length(); i++){
JSONObject jo = result.getJSONObject(i);
String idplace = jo.getString(konfigurasi.TAG_PLACE);
String titl = jo.getString(konfigurasi.TAG_TITLE);
String subj = jo.getString(konfigurasi.TAG_SUBJECT);
String desc= jo.getString(konfigurasi.TAG_DESCRIPTION);
String dateo = jo.getString(konfigurasi.TAG_DATEORDER);
HashMap<String,String> orders = new HashMap<>();
orders.put(konfigurasi.TAG_PLACE,idplace);
orders.put(konfigurasi.TAG_TITLE,titl);
orders.put(konfigurasi.TAG_SUBJECT,subj);
orders.put(konfigurasi.TAG_DESCRIPTION,desc);
orders.put(konfigurasi.TAG_DATEORDER,dateo);
list.add(orders);
}
} catch (JSONException e) {
e.printStackTrace();
}
ListAdapter adapter = new SimpleAdapter(
DateEventActivity.this, list, R.layout.list_item,
new String[]{konfigurasi.TAG_PLACE,konfigurasi.TAG_TITLE,konfigurasi.TAG_SUBJECT,konfigurasi.TAG_DESCRIPTION,konfigurasi.TAG_DATEORDER},
new int[]{R.id.idplace, R.id.titl, R.id.subj, R.id.desc, R.id.dateo});
listView.setAdapter(adapter);
}
private void getJSON(){
class GetJSON extends AsyncTask<Void,Void,String> {
ProgressDialog loading;
#Override
protected void onPreExecute() {
super.onPreExecute();
loading = ProgressDialog.show(DateEventActivity.this,"Mengambil Data","Mohon Tunggu...",false,false);
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
loading.dismiss();
JSON_STRING = s;
showOrder();
}
#Override
protected String doInBackground(Void... params) {
RequestHandler rh = new RequestHandler();
String s = rh.sendGetRequest(konfigurasi.URL_GET_ALL);
return s;
}
}
GetJSON gj = new GetJSON();
gj.execute();
}
I'm developing an app that takes data from a website with JSoup. I was able to get the normal data.
But now I need to implement a pagination on it. I was told it would have to be with Web Driver, Selenium. But I do not know how to work with him, could someone tell me how I can do it?
public class MainActivity extends AppCompatActivity {
private String url = "http://www.yudiz.com/blog/";
private ArrayList<String> mAuthorNameList = new ArrayList<>();
private ArrayList<String> mBlogUploadDateList = new ArrayList<>();
private ArrayList<String> mBlogTitleList = new ArrayList<>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
new Description().execute();
}
private class Description extends AsyncTask<Void, Void, Void> {
#Override
protected Void doInBackground(Void... params) {
try {
// Connect to the web site
Document mBlogDocument = Jsoup.connect(url).get();
// Using Elements to get the Meta data
Elements mElementDataSize = mBlogDocument.select("div[class=author-date]");
// Locate the content attribute
int mElementSize = mElementDataSize.size();
for (int i = 0; i < mElementSize; i++) {
Elements mElementAuthorName = mBlogDocument.select("span[class=vcard author post-author test]").select("a").eq(i);
String mAuthorName = mElementAuthorName.text();
Elements mElementBlogUploadDate = mBlogDocument.select("span[class=post-date updated]").eq(i);
String mBlogUploadDate = mElementBlogUploadDate.text();
Elements mElementBlogTitle = mBlogDocument.select("h2[class=entry-title]").select("a").eq(i);
String mBlogTitle = mElementBlogTitle.text();
mAuthorNameList.add(mAuthorName);
mBlogUploadDateList.add(mBlogUploadDate);
mBlogTitleList.add(mBlogTitle);
}
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void result) {
// Set description into TextView
RecyclerView mRecyclerView = (RecyclerView)findViewById(R.id.act_recyclerview);
DataAdapter mDataAdapter = new DataAdapter(MainActivity.this, mBlogTitleList, mAuthorNameList, mBlogUploadDateList);
RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(getApplicationContext());
mRecyclerView.setLayoutManager(mLayoutManager);
mRecyclerView.setAdapter(mDataAdapter);
}
}
}
Problem statement (as per my understanding): Scraper should be able to go to the next page until all pages are done using the pagination options available at the end of the blog page.
Now if we inspect the next button in the pagination, we can see the following html.
a class="next_page" href="http://www.yudiz.com/blog/page/2/"
Now we need to instruct Jsoup to pick up this dynamic url in the next iteration of the loop to scrap data. This can be done using the following approach:
String url = "http://www.yudiz.com/blog/";
while (url!=null){
try {
Document doc = Jsoup.connect(url).get();
url = null;
System.out.println(doc.getElementsByTag("title").text());
for (Element urls : doc.getElementsByClass("next_page")){
//perform your data extractions here.
url = urls != null ? urls.absUrl("href") : null;
}
} catch (IOException e) {
e.printStackTrace();
}
}
I've got this code with fetches the "rate" data from an API, along with "rate", I need to get the "name". If I get "name" it often binds it below the "rate".
I need it to join on the same row of the List View, so it is like [Rate Name].
I need to get two objects of a JSON Array and bind it to the array adapter so I can display two objects in the same row of a List View so it is more user friendly.
The code below is of the AsyncTask, the code works fine but I need to add one more object and make sure it is displayed as one rate - one name and then iterating through the loop and adding more as needed in the same order.
public class AsyncTaskParseJson extends AsyncTask<String, String, String> {
// the url of the web service to call
String yourServiceUrl = "eg: URL";
#Override
protected void onPreExecute() {
}
String filename = "bitData";
#Override
protected String doInBackground(String... arg0) {
try {
// create new instance of the httpConnect class
httpConnect jParser = new httpConnect();
// get json string from service url
String json = jParser.getJSONFromUrl(yourServiceUrl);
// parse returned json string into json array
JSONArray jsonArray = new JSONArray(json);
// loop through json array and add each currency to item in arrayList
//Custom Loop Initialise
for (int i = 1; i < 8; i++) {
JSONObject json_message = jsonArray.getJSONObject(i);
// The second JSONObject which needs to be added
JSONObject json_name = jsonArray.getJSONObject(i);
if (json_message != null) {
//add each currency to ArrayList as an item
items.add(json_message.getString("rate"));
String bitData = json_message.getString("rate");
String writeData = bitData + ',' +'\n';
FileOutputStream outputStream;
File file = getFileStreamPath(filename);
// first check if file exists, if not create it
if (file == null || !file.exists()) {
try {
outputStream = openFileOutput(filename, MODE_PRIVATE);
outputStream.write(writeData.getBytes());
outputStream.write("\r\n".getBytes());
outputStream.close();
} catch (Exception e) {
e.printStackTrace();
}
}
// if file already exists then append bit data to it
else if (file.exists()) {
try {
outputStream = openFileOutput(filename, Context.MODE_APPEND);
outputStream.write(writeData.getBytes());
outputStream.write("\r\n".getBytes());
outputStream.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
// below method will run when service HTTP request is complete, will then bind text in arrayList to ListView
#Override
protected void onPostExecute(String strFromDoInBg) {
ListView list = (ListView) findViewById(R.id.rateView);
ArrayAdapter<String> rateArrayAdapter = new ArrayAdapter<String>(BitRates.this, android.R.layout.simple_expandable_list_item_1, items);
list.setAdapter(rateArrayAdapter);
}
}
Just Create Custom Class Messsage:
public class Item{
private String name;
private String rate;
public void Message(String n, String r){
this.name=n;
this.rate=r;
}
// create here getter and setter
}
Now in your background, you have to add name and rate in Message class
Public class MainAcitity extends Activity{
public static List<Item> items= new ArrayList<>();// define in inside the class
// this has to be down on background
Item i=new Item(json_message.getString("name"),json_message.getString("rate"));
items.add(i);
Now pass this listmessge onPostExecute :
ListView list = (ListView) findViewById(R.id.rateView);
ArrayAdapter<String> rateArrayAdapter = new ArrayAdapter<String>(BitRates.this, android.R.layout.simple_expandable_list_item_1, items);
list.setAdapter(rateArrayAdapter);
Is that any helpful for you.
Follow this link.You will get my point.
https://devtut.wordpress.com/2011/06/09/custom-arrayadapter-for-a-listview-android/
I have a JSONObject in my MainActivity under a function and I want to use it outside the function and in another class, how can I do that?
I want to make this variable public, here is the code :
public void ListDrwaer() {
List<Map<String, String>> productList = new ArrayList<Map<String, String>>();
try {
JSONObject jsonResponse = new JSONObject(jsonResult);
JSONArray jsonMainNode = jsonResponse.optJSONArray("products");
for (int i = 0; i < jsonMainNode.length(); i++) {
JSONObject jsonChildNode = jsonMainNode.getJSONObject(i);
}
// System.out.println("*****JARRAY*****" + jsonMainNode.getJSONObject(0));
List<Map<String, String>> productLista = new ArrayList<Map<String, String>>();
JSONObject pro1 = jsonMainNode.getJSONObject(1);
String data = pro1.getString("name");
// System.out.println("*****JARRAY*****" + data);
System.out.println("*****JARRAY*****" + pro1);
} catch (JSONException e) {
Toast.makeText(getApplicationContext(), "Error" + e.toString(),
Toast.LENGTH_SHORT).show();
}
I want to make pro1 (which is JSONObject) public and use it outside public void and also use it in another class.
Can I do that using put or add?
try code below, it might help..
Intent intent = new Intent(getBaseContext(), SignoutActivity.class);
intent.putExtra("EXTRA_SESSION_ID", sessionId);
startActivity(intent);
You will need to create the variable first outside any method like this
Static JSONObject pro1;
and then acces it simple by using
classname.pro1
you can declare that variable public.
just put
public static JSONObject pro1;
to your class declaration.
2. that is not safe because of:
1. that variable will vanish if your app will be killed and recreated by Android system.
2. you should be carefull when accessing that variable from other threads.
Updated Question from previous: I filled an array through HashMap, Iam using Asynctask for http request & after filling array put that array in dialog box. When I first run my app it gives me an empty dialog box & didn't give any error but when I re run my app it shows all array elements in dialog box perfectly. Whats the reason ?
//JsonResponse Inner Class in main class
private class JsonResponse extends AsyncTask<String, Void, String>
{
String response = "";
private ArrayList<HashMap<String, String>> prServices_resultList =
new ArrayList<HashMap<String, String>>();
protected void onPostExecute(String result)
{
if(response.equalsIgnoreCase("Success"))
{
ResultList_List = prServices_resultList;
int s=0;
for (HashMap<String, String> hashServices : prServices_resultList)
{
Db_Services[s] = hashServices.get(android_S_CName);
Db_ServicesID[s] = hashServices.get(android_S_ID);
s++;
}
}
}
protected String doInBackground(final String... args)
{
JSONParser jParser = new JSONParser();
JSONArray jArrayServices = jParser.getJSONFromUrl(url_Services);
try
{
for (int i = 0; i < jArrayServices.length(); i++)
{
JSONObject jsonElements = jArrayServices.getJSONObject(i);
String S_id = jsonElements.getString(android_S_ID);
String S_name = jsonElements.getString(android_S_NAME);
HashMap<String, String> hashServices = new HashMap<String, String>();
// adding each child node to HashMap key
hashServices.put(android_S_ID, S_id);
hashServices.put(android_S_NAME, S_name);
// adding HashList to ArrayList
prServices_resultList.add(hashServices);
}
response = "Success";
}
catch(JSONException e)
{
e.printStackTrace();
}
return response;
}
}
In my main class have have a button & when i press i execute AsyncTask:
new JsonResponse().execute;
In main class above onCreate i declare like:
static ArrayList<HashMap<String, String>> ResultList_Services =
new ArrayList<HashMap<String, String>>();
String[] Db_Services = new String[ResultList_Services.size()];
String[] Db_ServicesID = new String[ResultList_Services.size()];
You are creating an empty map here:
ResultList_Services = new ArrayList<HashMap<String, String>>();
Then trying to initialize two arrays with the size of an empty map - being zero.
// ResultList_Services.size() will be zero
String[] Db_Services = new String[ResultList_Services.size()];
String[] Db_ServicesID = new String[ResultList_Services.size()];
So when you try adding to these arrays it will throw an OutOfBoundsException
You could make these Arrays into lists, then you can dynamically add elements as needed without needing to specify a size to start with. If you then need an Array (for other Methods) you can get an array from a list using List#toArray()
As per your comment
You could just create temporary arrays to which you add all the elements and then assign this to your other arrays, something like
protected void onPostExecute(String result)
{
if(response.equalsIgnoreCase("Success"))
{
ResultList_List = prServices_resultList;
String[] tmp_dbServ = new String[prServices_resultList.size()];
String[] tmp_dbServID = new String[prServices_resultList.size()];
int s=0;
for (HashMap<String, String> hashServices : prServices_resultList)
{
tmp_dbServ[s] = hashServices.get(android_S_CName);
tmp_dbServID[s] = hashServices.get(android_S_ID);
s++;
}
Db_Services = tmp_dbServ;
Db_ServicesID = tmp_dbServID;
}
}