Android Database in AsyncTask in Fragment - android

I have a DbHelper Class which extends SQLiteOpenHelper.
I do Some Download and update the Database inside an Asynctask.
Inside an activity i got no problem and code works fine,
but when i use the ASynctask class inside a fragment problems occurs.
usually wherever i use a context an Exception happened, Especially with dbHelper.ClearDB()
Error:
DB Read ERROR:java.lang.NullPointerException:
Attempt to invoke virtual method 'java.util.ArrayList x.database.DBHelper.getAllItems()' on a null object reference
Here's the code :
public class StaggeredFragment extends Fragment
{
private DBHelper dbHelper;
private SharedPreferences preferences;
private ArrayList<DisItem> savedData;
private final String LINK1 = "myLink";
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
dbHelper = new DBHelper(getActivity().getApplicationContext());
preferences = getActivity().getSharedPreferences("pid", Context.MODE_PRIVATE);
new LoaderAsyncTask("ALL").execute();
}
class LoaderAsyncTask extends AsyncTask<Void, Void, Boolean> {
String brand;
LoaderAsyncTask(String brand) {
this.brand = brand;
}
#Override
protected Boolean doInBackground(Void... params) {
Log.d(TAG,"RUnning");
String fetched;
InputStream is = null;
//Store Current Data before Sync
try {
savedData = dbHelper.getAllItems();
}catch (Exception e)
{
Log.d(TAG,"DB Read ERROR:"+e.toString());
return false;
}
try {
dbHelper.ClearDB();
}catch (Exception e)
{
Log.d(TAG,"DB Clear ERROR:"+e.toString());
return false;
}
// Open connection to server for html
try {
is = urlStream(LINK1);
} catch (Exception e) {
Log.e(TAG, "HTTP Error " + e.toString());
return false;
}
// Fetch HTML Data
try {
fetched = readIt(is);
// Log.d("fetched", fetched);
} catch (Exception e) {
Log.e(TAG, "Buffer Error " + e.toString());
return false;
}
// Parsing JSON
try {
if (!fetched.isEmpty())
InitialsJson(fetched);
}catch (JSONException e) {
Log.e(TAG, "JSON Error " + e.toString());
return false;
}
return true;
}
#Override
protected void onPostExecute(Boolean aBoolean) {
super.onPostExecute(aBoolean);
if(!aBoolean)
RestoreData();
}
}
private void InitialsJson(String fetched) throws JSONException
{
JSONObject jsonObject = new JSONObject(fetched);
if (jsonObject.getInt("success") == 1) {
JSONArray array = jsonObject.getJSONArray("data");
for (int i = 0; i<array.length() ; i++) {
JSONObject object = array.getJSONObject(i);
DisItem disItem = new DisItem();
disItem.setPid(object.getString("pid"));
disItem.setLiked(preferences.getBoolean(String.valueOf(disItem.getPid()), false));
Log.d(TAG, disItem.toString());
dbHelper.insert(disItem);
}
}
}
This is Databace getallItems function
public ArrayList<DisItem> getAllItems()
{
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery("select * from " + DIS_TABLE_NAME + "", null);
ArrayList<DisItem> arrayList = new ArrayList<>();
cursor.moveToFirst();
while (! cursor.isAfterLast())
{
DisItem disItem = new DisItem(cursor);
arrayList.add(disItem);
cursor.moveToNext();
}
return arrayList;
}

I tried your code with same scenario in a small JUnit Test and it shows me that you have not initialized your ArrayList<DisItem> correctely in getAllItems() method may be thats why you are getting nullPointerException that is
Replace
ArrayList<DisItem> arrayList = new ArrayList<>();
With
ArrayList<DisItem> arrayList = new ArrayList<DisItem>();'
I corrected this thing and run the test again with some dummy values and it showed me correct result like:
public class Test
{
private ArrayList<DisItem> savedData;
#org.junit.Test
public void test() throws Exception
{
savedData = getAllData();
for(int a = 0; a < savedData.size(); a++){
System.out.println("ArrayList Data A= " + savedData.get(a).getA() + " B = " + savedData.get(a).getB());
}
}
}
private ArrayList<DisItem> getAllData()
{
ArrayList<DisItem> arrayList = new ArrayList<DisItem>();
DisItem disItem = new DisItem();
disItem.setA("AAAAAA");
disItem.setB("BBBB");
arrayList.add(disItem);
return arrayList;
}
private class DisItem
{
String a, b;
public void setA(String a)
{
this.a = a;
}
public void setB(String b)
{
this.b = b;
}
public String getA()
{
return this.a;
}
public String getB()
{
return this.b;
}
}
Output:
ArrayList Data A= AAAAAA B = BBBB

you cant access more than one SharedPreferences or SQLiteOpenHelper in Parallel.

Related

Android TableView with MSSQL

I am busy with trying to get an array which i get from MSSQL to display in a table view form in my application. I have tried to google it but i cant seem to find an example of this. I have tried it but i am running into one small error.
I get the following error Cannot resolve constructor:Simpletabledata adapter[package.mainactivity, package.itemarray]
Here is my mainactivy.java class:
public class MainActivity extends AppCompatActivity {
static String[] spaceProbeHeaders={"Name"};
private ArrayList<ClassListItems> itemArrayList; //List items Array
private MyAppAdapter myAppAdapter; //Array Adapter
final TableView<String[]> tableView = (TableView<String[]>) findViewById(R.id.tableView);
private boolean success = false; // boolean
Connection conn; // Connection Class Initialization
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tableView.setHeaderBackgroundColor(Color.parseColor("#777777"));
tableView.setHeaderAdapter(new SimpleTableHeaderAdapter(this,spaceProbeHeaders));
tableView.setColumnCount(4);
itemArrayList = new ArrayList<ClassListItems>(); // Arraylist Initialization
// Calling Async Task
SyncData orderData = new SyncData();
orderData.execute("");
}
// Async Task has three overrided methods,
private class SyncData extends AsyncTask<String, String, String>
{
String msg = "Internet/DB_Credentials/Windows_FireWall_TurnOn Error, See Android Monitor in the bottom For details!";
ProgressDialog progress;
#Override
protected void onPreExecute() //Starts the progress dailog
{
progress = ProgressDialog.show(MainActivity.this, "Synchronising",
"Tableview Loading! Please Wait...", true);
}
#Override
protected String doInBackground(String... strings) // Connect to the database, write query and add items to array list
{
try
{
ConnectionClass conStr=new ConnectionClass();
conn =conStr.connectionclass();
//Connection Object
if (conn == null)
{
success = false;
}
else {
// Change below query according to your own database.
String query = "SELECT customer_first_name FROM cc_customer";
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery(query);
if (rs != null) // if resultset not null, I add items to itemArraylist using class created
{
while (rs.next())
{
try {
itemArrayList.add(new ClassListItems(rs.getString("customer_first_name")));
} catch (Exception ex) {
ex.printStackTrace();
}
}
msg = "Found";
success = true;
} else {
msg = "No Data found!";
success = false;
}
}
} catch (Exception e)
{
e.printStackTrace();
Writer writer = new StringWriter();
e.printStackTrace(new PrintWriter(writer));
msg = writer.toString();
success = false;
}
return msg;
}
#Override
protected void onPostExecute(String msg) // disimissing progress dialoge, showing error and setting up my listview
{
progress.dismiss();
Toast.makeText(MainActivity.this, msg + "", Toast.LENGTH_LONG).show();
if (success == false)
{
}
else {
try {
//myAppAdapter = new MyAppAdapter(itemArrayList, MainActivity.this);
tableView.setDataAdapter(new SimpleTableDataAdapter(MainActivity.this,itemArrayList ));
} catch (Exception ex)
{
}
}
}
}
and here is my classlist.java file:
public class ClassListItems
{
public String name; //Name
public ClassListItems(String name)
{
this.name = name;
}
public String getName() {
return name;
}
Update
N.B: OP is using SortableTableView Library.
You need to import the following to solve Cannot resolve constructor:SimpleTableDataAdapter-
import de.codecrafters.tableview.toolkit.SimpleTableDataAdapter;
Original
Do you have SimpleTableDataAdapter class in your project? It seems it can't find the class so it is not in the same package. If it is in different package, you need to import it.
And on a different note, your .java file names should match the class name
And on another different note, have you tested that itemArrayList is actually populating? For Android-MSSQL, here is a tutorial pointer -
https://parallelcodes.com/connect-android-to-ms-sql-database-2/
There are many tutorials if you google it.

Downloading data from server and add this data to local database with sync

I'm developing my app, in which storing quotes.
Data about quotes I download from my server.
I want in order to user downloading 10 quotes (at that time data add to local database), and if he scrolled this 10 quotes, new data will be download (again 10).
For example, as in facebook tape (with adding data to local db).
But I also need sync local db with server db.
I do not understand how to combine all this.
Download data - Here I pass the id from which to download from the id from server db.
class DownloadAndParseJson extends AsyncTask<Integer, Void, ArrayList<QuoteObject>> {
interface AsyncResponse {
void processFinish(ArrayList<QuoteObject> output);
}
private AsyncResponse delegate = null;
DownloadAndParseJson(AsyncResponse delegate){
this.delegate = delegate;
}
private static final String TAG = "###" + "DownloadAndParseJson";
#Override
protected ArrayList<QuoteObject> doInBackground(Integer... params) {
Log.i(TAG, "Starting download quotes from " + params[0] + " id");
if (params.length == 0) {
return null;
}
int id = params[0];
HttpURLConnection urlConnection = null;
BufferedReader reader = null;
String countriesJsonStr = null;
try {
final String BASIC_URL = "http://*******.com";
final String ID_PARAM = "id";
Uri builtUri = Uri.parse(BASIC_URL).buildUpon()
.appendQueryParameter(ID_PARAM, Integer.toString(id))
.build();
URL url = new URL(builtUri.toString());
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("GET");
urlConnection.connect();
InputStream inputStream = urlConnection.getInputStream();
StringBuffer buffer = new StringBuffer();
if (inputStream == null) {
return null;
}
reader = new BufferedReader(new InputStreamReader(inputStream));
String line;
while ((line = reader.readLine()) != null) {
buffer.append(line + "\n");
}
if (buffer.length() == 0) {
return null;
}
countriesJsonStr = buffer.toString();
Log.v(TAG, "download end");
} catch (IOException e) {
Log.e(TAG, "Error", e);
return null;
} finally {
if (urlConnection != null) {
urlConnection.disconnect();
}
if (reader != null) {
try {
reader.close();
} catch (final IOException e) {
Log.e(TAG, "Error", e);
}
}
}
Log.i(TAG, "End download quotes");
return getArrayParsedJson(countriesJsonStr);
}
#Override
protected void onPostExecute(ArrayList<QuoteObject> result) {
Log.i(TAG, "Downloaded " + result.size() + " quotes");
delegate.processFinish(result);
}
private ArrayList<QuoteObject> getArrayParsedJson(String jsonStr){
Gson gson = new Gson();
Type collectionType = new TypeToken<ArrayList<QuoteObject>>(){}.getType();
return gson.fromJson(jsonStr, collectionType);
}
}
Working with the database - here Im store Quote objects
public class RealmHelper {
private static final String TAG = "###" + "RealmHelper";
Context context;
public RealmHelper(Context context) {
this.context = context;
}
public void write(ArrayList<QuoteObject> quoteObjectArrayList) {
Realm.init(context);
Realm realm = Realm.getDefaultInstance();
realm.beginTransaction();
for (QuoteObject quoteObject : quoteObjectArrayList){
realm.copyToRealm(quoteObject);
}
realm.commitTransaction();
}
public ArrayList<QuoteObject> read() {
Realm.init(context);
Realm realm = Realm.getDefaultInstance();
return new ArrayList<>(realm.where(QuoteObject.class).findAll());
}
public void delete() {
Realm.init(context);
Realm realm = Realm.getDefaultInstance();
final RealmResults<QuoteObject> countries = realm.where(QuoteObject.class).findAll();
realm.executeTransaction(new Realm.Transaction() {
#Override
public void execute(Realm realm) {
countries.deleteAllFromRealm();
Log.i(TAG, "size = " + countries.size());
}
});
}
}
MainActivity
public class MainActivity extends AppCompatActivity
implements DownloadAndParseJson.AsyncResponse{
.
.
RVAdapter adapter;
private ArrayList<QuoteObject> quoteObjectArrayList;
.
.
protected void onCreate(){
.
.
.
RecyclerView recyclerView = (RecyclerView) findViewById(R.id.recyclerView);
recyclerView.setHasFixedSize(true);
LinearLayoutManager layoutManager = new LinearLayoutManager(this);
recyclerView.setLayoutManager(layoutManager);
adapter = new RVAdapter(this, quoteObjectArrayList);
recyclerView.setAdapter(adapter);
}
#Override
public void processFinish(ArrayList<QuoteObject> output) {
if (output.size() != 0) {
quoteObjectArrayList = output;
Log.i(TAG, "processFinish() returned outputArray size " + output.size());
} else
Toast.makeText(this, "Not found quotes", Toast.LENGTH_SHORT).show();
}
RecyclerView.Adapter - To display quotes Im using card view.
class RVAdapter extends RecyclerView.Adapter<RVAdapter.PersonViewHolder>
implements DownloadAndParseJson.AsyncResponse{
private static final String TAG = "###" + "RVAdapter";
private Context context;
private boolean hasMoreItems;
private ArrayList<QuoteObject> quoteObjectArrayList;
RVAdapter(Context context, ArrayList<QuoteObject> quoteObjectArrayList){
this.context = context;
this.hasMoreItems = true;
this.quoteObjectArrayList = quoteObjectArrayList;
Log.i(TAG, "quoteObjectArrayList = " + quoteObjectArrayList.size());
}
private void notifyNoMoreItems(){
hasMoreItems = false;
Toast.makeText(context, "No More Items", Toast.LENGTH_SHORT).show();
}
#Override
public RVAdapter.PersonViewHolder onCreateViewHolder(ViewGroup viewGroup, int viewType) {
View view = LayoutInflater.from(viewGroup.getContext())
.inflate(R.layout.card_of_quote, viewGroup, false);
return new PersonViewHolder(view);
}
#Override
public void onBindViewHolder(final RVAdapter.PersonViewHolder holder, int position) {
Log.i(TAG, "Card position = " + position);
if (position == quoteObjectArrayList.size() && hasMoreItems){
new DownloadAndParseJson(this).execute(Integer.parseInt(quoteObjectArrayList.get(position).getId()));
}
holder.contentOfQuote.setText(quoteObjectArrayList.get(position).getQuote());
holder.authorQuote.setText(quoteObjectArrayList.get(position).getAuthor());
holder.ratingBar.setOnRatingChangeListener(new MaterialRatingBar.OnRatingChangeListener() {
#Override
public void onRatingChanged(MaterialRatingBar ratingBar, float rating) {
//ratingBar.setRight(Integer.parseInt(quoteObjectArrayList.get(position).getId()));
}
});
holder.btnShareQuote.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent sendIntent = new Intent();
sendIntent.setAction(Intent.ACTION_SEND);
sendIntent.putExtra(Intent.EXTRA_TEXT, holder.contentOfQuote.getText()
+ "\n" + holder.authorQuote.getText() );
sendIntent.setType("text/plain");
context.startActivity(sendIntent);
}
});
holder.btnViewComment.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//View Comments
}
});
}
#Override
public int getItemCount() {
return quoteObjectArrayList.size();
}
#Override
public void processFinish(ArrayList<QuoteObject> output) {
if (output.size() != 0) {
quoteObjectArrayList.addAll(output);
Log.i(TAG, "Total quoteArray Size = " + quoteObjectArrayList.size());
new RealmHelper(context).write(output); // NEED separate throw
} else notifyNoMoreItems();
}
static class PersonViewHolder extends RecyclerView.ViewHolder {
CardView cardView;
TextView contentOfQuote, authorQuote;
MaterialRatingBar ratingBar;
ImageButton btnViewComment, btnShareQuote;
TextView rating;
public PersonViewHolder(View itemView) {
super(itemView);
this.cardView = (CardView) itemView.findViewById(R.id.cardView);
this.contentOfQuote = (TextView) itemView.findViewById(R.id.contentOfQuote);
this.authorQuote = (TextView) itemView.findViewById(R.id.authorQuote);
this.btnViewComment = (ImageButton) itemView.findViewById(R.id.btnViewComment);
this.btnShareQuote = (ImageButton) itemView.findViewById(R.id.btnShareQuote);
this.ratingBar = (MaterialRatingBar) itemView.findViewById(R.id.ratingBar);
this.rating = (TextView) itemView.findViewById(R.id.txtRating);
}
}
}
Now I need to combine all this.
It should turn out:
To start with the data from local db.
If there is no data - download new (10 quotes).
Else take data from local db until they run out
Download 10 quotes from server bd, add to local and display they.
Or If there is no data Print out about it.
Sync local bd with server.
Help me please.
Thanks.
This would be much easier if you used RealmResults as intended along with RealmChangeListener and Realm's notification system. See the official documentation.
class DownloadAndParseJson extends AsyncTask<Integer, Void, Void> {
DownloadAndParseJson(){
}
private static final String TAG = "###" + "DownloadAndParseJson";
#Override
protected Void doInBackground(Integer... params) {
Log.i(TAG, "Starting download quotes from " + params[0] + " id");
if (params.length == 0) {
return null;
}
int id = params[0];
try {
final List<QuoteObject> quotes = retrofitService.getQuotes(id).execute().body();
if(quotes == null) {
throw new RuntimeException("Download failed");
}
try(Realm realm = Realm.getDefaultInstance()) {
realm.executeTransaction(new Realm.Transaction() {
#Override
public void execute(Realm realm) {
realm.insert(quotes);
}
});
}
} catch (Exception e) {
Log.e(TAG, "Error", e);
return null;
}
Log.i(TAG, "End download quotes");
return null;
}
#Override
protected void onPostExecute(Void ignored) {
}
}
And
class RVAdapter extends RealmRecyclerViewAdapter<QuoteObject, RVAdapter.PersonViewHolder> {
private static final String TAG = "###" + "RVAdapter";
RVAdapter(OrderedRealmCollection<QuoteObject> quotes) {
super(quotes, true);
}
// onCreateViewHolder
// onBindViewHolder
// view holder
}
And
RecyclerView recyclerView = (RecyclerView) findViewById(R.id.recyclerView);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
adapter = new RVAdapter(realm.where(QuotesObject.class).findAll()); // <-- RealmResults
recyclerView.setAdapter(adapter);
and some "did download all" kind of logic, although that needs a bit smarter error handling; and "is data being downloaded" so that you don't spam requests when you scrolled down.

What ActivityProxyHelper class actually do?

I need help to understand what is going on in the following two classes. The first activity class is the launching activity.
public class UnityPlayerNativeActivity
extends com.unity3d.player.UnityPlayerNativeActivity
{
private ActivityProxyObjectHelper _proxyHelper;
protected void onCreate(Bundle paramBundle)
{
super.onCreate(paramBundle);
try
{
this._proxyHelper = new ActivityProxyObjectHelper(this);
this._proxyHelper.onCreate(paramBundle);
return;
}
catch (Exception paramBundle)
{
Log.i("Prime31", "Failed to create proxyHelper: " + paramBundle.getMessage());
}
}
}
And the second class is :
public class ActivityProxyObjectHelper
{
private Activity _context;
private List<Class<?>> _proxyClasses = new ArrayList();
public ActivityProxyObjectHelper(Activity paramActivity)
{
this._context = paramActivity;
}
protected void onCreate(Bundle paramBundle)
{
for (;;)
{
try
{
localObject1 = this._context.getPackageManager().getApplicationInfo(this._context.getPackageName(), 128).metaData;
localObject2 = ((Bundle)localObject1).keySet().iterator();
bool = ((Iterator)localObject2).hasNext();
if (bool) {
continue;
}
}
catch (PackageManager.NameNotFoundException localNameNotFoundException)
{
Object localObject1;
boolean bool;
String str;
Log.i("Prime31", "Failed to load meta-data, NameNotFound: " + localNameNotFoundException.getMessage());
continue;
}
catch (NullPointerException localNullPointerException)
{
Log.e("Prime31", "Failed to load meta-data, NullPointer: " + localNullPointerException.getMessage());
continue;
Object localObject2 = (Class)localNullPointerException.next();
try
{
((Class)localObject2).getMethod("onCreate", new Class[] { Bundle.class }).invoke(null, new Object[] { paramBundle });
}
catch (Exception localException1) {}
continue;
}
if (((Iterator)localObject1).hasNext()) {
continue;
}
return;
str = (String)((Iterator)localObject2).next();
}
}
}
I need to understand what is that ActivityProxyObjectHelper class doing initially after the launching activity gets called. What is the purpose of this class? Why it is trying to get metadata? What is localObject1 and localObject2 trying to do?

Get too many results

I'm trying to create Favorites class. I search for title I get from the user and adds the video to the Favorites class. But, I always get more than one result. ( I get the maximum results which is 10 ).
How can I get only 1 result for each title?
This is the on create:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.favorites_layout);
getSupportActionBar().setTitle("Favorites");
initializeViews();
extras = getIntent().getExtras();
this.vidTitle = extras.getString("title");
this.vidID = extras.getString("id");
//Checking where to add the new Video
for(int i=0;i<favorites.length;i++){
if(favorites[i]==null){
favorites[i] = vidTitle;
}
break; // Break so it won't add same video to all array
}
AppUtils.showToast("Loading Favorites");
getVideo2();
}
This is the code which gets the 10 results:
public void getVideo(){
AppUtils.showToast("Loading Favorites");
mServiceTask = new ServiceTask(SEARCH_VIDEO);
mServiceTask.setmServerResponseListener(this);
for (int i=0; i<favorites.length;i++) {
if(favorites[i]!=null){
mServiceTask.execute(new Object[]{favorites[i]}); <--- Problem here
break;
}
else{
break;
}
}
}
ServiceTask:
public class ServiceTask extends AsyncTask<Object, Void, Object[]> implements ServiceTaskInterface{
private static final String TAG = ServiceTask.class.getSimpleName();
private ServerResponseListener mServerResponseListener = null;
private int mRequestCode = 0;
public void setmServerResponseListener(ServerResponseListener mServerResponseListener){
this.mServerResponseListener = mServerResponseListener;
}
public ServiceTask(int iReqCode){
mRequestCode = iReqCode;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
mServerResponseListener.prepareRequest(mRequestCode);
}
#Override
protected Object[] doInBackground(Object... params) {
if(params == null)
throw new NullPointerException("Parameters to the async task can never be null");
mServerResponseListener.goBackground();
Object[] resultDetails = new Object[2];
resultDetails[0] = mRequestCode;
switch (mRequestCode){
case AppConstants.SEARCH_VIDEO:
try {
resultDetails[1] = loadVideos((String) params[0]);
break;
}catch (Exception e){
AppUtils.showToast("BLABLABLA");}
}
return resultDetails;
}
#Override
protected void onPostExecute(Object[] result) {
super.onPostExecute(result);
mServerResponseListener.completedRequest(result);
}
//Loading the videos, with help of Google's code.
private List<SearchResult> loadVideos(String queryTerm){
try{
YouTube youTube = new YouTube.Builder(transport,jsonFactory,new HttpRequestInitializer() {
#Override
public void initialize(HttpRequest httpRequest) throws IOException {}
}).setApplicationName(YoutubeApplication.appName()).build();
YouTube.Search.List search = youTube.search().list("id,snippet");
search.setKey(AppConstants.KEY);
search.setQ(queryTerm);
//Only including videos
search.setType("video");
search.setFields("items(id/kind,id/videoId,snippet/title,snippet/description,snippet/thumbnails/default/url,snippet/thumbnails/medium/url)");
search.setMaxResults(AppConstants.NUMBER_OF_VIDEOS_RETURNED);
//Call the API to print results
SearchListResponse searchListResponse = search.execute();
List<SearchResult> searchResultList = searchListResponse.getItems();
if(searchResultList != null){
return searchResultList;
}
}catch (GoogleJsonResponseException e){
System.err.println("There was a service error: " + e.getDetails().getCode() + " : "
+ e.getDetails().getMessage());
}catch (IOException e){
System.err.println("There was an IO error: " + e.getCause() + " : " + e.getMessage());
}catch (Throwable t){
t.printStackTrace();
}
return null;
}
}
How can I get only 1 result at time but still have place for 10 results ( like 10 different videos) ?
At first, comment your break; lines or your loop is useless. Then collect your not null objects in list and place it in execute method with toArray.
LinkedList<Object> list = new LinkedList<Object>();
for (int i=0; i<favorites.length; i++) {
if(favorites[i]!=null){
//mServiceTask.execute(new Object[]{favorites[i]}); //<--- Problem here
list.add(favorites[i]);
//break;
}
else{
//break;
}
}
mServiceTask.execute(list.toArray());
UPDATE
And about ServiceTask class. In doInBackground you are using only params[0] - the first array element. So there should be:
for (int i=0; i<params.length; i++) {
loadVideos((String) params[i]);
}

How to use returned arraylist?How to retrieve data from arraylist?

In the following code,i am saving the three values fun_id,fun_logo,fun_req with the help of another class Use.In the code an arraylist is returned,now i want to retrieve the fun_id,fun_logo,fun_req.I want to add fun_logo into imagearray.I would like to know how to use the Class Use for retreving data.I am learning currently so only small idea bout android.
ArrayList<Use> stringArrayList = null;
ArrayList<Use> res = null;
ArrayList<String> linklist = null;
String getdetailsurl;
String link [];
String[] ar;
Use[] getalldet;
public String imagearray[];
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
new Getdetailsfromweb().execute();
list=(ListView)findViewById(R.id.listView1);
// adapter=new myadpter(this, imagearray);
list.setAdapter(adapter);
}
public class Getdetailsfromweb extends AsyncTask<String,Void,String>
{
String result = "";
#Override
protected String doInBackground(String... params) {
getdetailsurl=Webcall.getdet();
if(getdetailsurl!=null)
{
result = "Success";
}
else
{
result = "Failure";
}
return result;
}
#Override
protected void onPostExecute(String result) {
res = new ArrayList<Use>();
try {
if (result.contentEquals("Success"))
{
res=passdetails();
System.out.println("lsize is " + res.size());
for(int i=0;i<res.size();i++)
{
// To retreive value what should i do here
imagearray[i]=obj.funlogo;
System.out.println("logo is " + imagearray[i]);
}
}
else
{
}
} catch (Exception e1) {
e1.printStackTrace();
}
}
public ArrayList<Use> passdetails()
{
JSONArray array = null;
stringArrayList = new ArrayList<Use>();
linklist= new ArrayList<String>();
Use usee;
try {
array = new JSONArray(getdetailsurl);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
for(int i = 0;i <array.length() ;i++ )
{
String fun_id= null;
String fun_logo= null;
String fun_req = null;
try {
fun_id = array.getJSONObject(i).getString("up_id");
System.out.println("up_id is " + fun_id);
fun_logo=array.getJSONObject(i).getString("logo");
System.out.println("logo is " + fun_logo);
fun_req=array.getJSONObject(i).getString("requirements");
System.out.println("req is " + fun_req);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
usee=new Use();
usee.funid=fun_id;
System.out.println("fun is " + usee.funid);
usee.funlogo=fun_logo;
System.out.println("fun is " + usee.funlogo);
usee.funreq=fun_req;
System.out.println("fun is " + usee.funreq);
linklist.add(fun_logo);
stringArrayList.add(usee);
}
return stringArrayList;
}
}
Use.java
public class Use {
public static String funid;
public String funlogo;
public String funreq;
}
I would like to know how to use the Class Use for retrieving data
All fields are public in Use and res is ArrayList of object of Use class. access values from each object as :
for(int i=0;i<res.size();i++)
Use useObj=res.get(i);
String funlogo=useObj.funlogo;
String funreq=useObj.funreq;
...
}
Define a Use class with getter and setter methods.
Define a method getFunLogos() in Use class which would return the image array of all the fun logos. Access this method from wherever you want.
protected String[] getFunLogos(ArrayList<Use> listFunLogos) {
for(int i=0;i<res.size();i++)
{
// To retreive value what should i do here
imagearray[i]=obj.funlogo;
System.out.println("logo is " + imagearray[i]);
}
}
I want to add fun_logo into imagearray
//linklist : as you are adding fun_log in it
imagearray=new String[linklist.size()];
linklist.toArray(imageArray);

Categories

Resources