I have pasted my code below and would appreciate it if someone would help me work through it. When I run my activity a list should be getting updated inside of my app. I haven't been able to pull in any data though. When I log first I get [] and nothing else. If I check the size it comes back as 0.
*I am expecting to retrieve the id, name, and size and place them in textviews within a listview.
When I access my URL string from my browser I get this:
{ "begin":
[
{"id":1,"name":"1","size":2},
{"id":2,"name":"2","size":2}],
"end":
[
{"id":1,"name":"1","size":2},
{"id":2,"name":"2","size":2}
]
}
models/Main.java
import android.content.Context;
import ...Cement;
import ...utils.NetworkUtilities;
import ...utils.ServerErrorException;
import com.google.gson.Gson;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;
import java.util.ArrayList;
import java.util.List;
public class Main {
private String id;
private String name;
private static List<Main> first;
public Main() {}
public String getId() {
return id;
}
public String getName() {
return name;
}
/**
* #return array of Main.
* #throws JSONException
*/
public static List<Main> updateMain(Context context) throws JSONException, ServerErrorException {
List<NameValuePair> params = new ArrayList<NameValuePair>();
if( Member.session(context) != null ) {
params(new BasicNameValuePair(Cement.ACCESS_CODE, Member.session(context).getAccessCode()));
} else {
return null;
}
String URL = Cement.BASE_URL + Cement.MAIN_URI;
String jsonString = NetworkUtilities.SendHttpGet(URL, params);
if (jsonString == null) return main(context);
JSONParse parser = new JsonParser();
JSONObject jsonObject = parser.parse(jsonString).getAsJsonObject();
if (jsonObject != null && jsonObject.get("begin") != null) {
Gson gson = new Gson();
for (JSONElement mainObject : jsonObject.get("begin").getAsJsonArray()) {
Main spot = gson.fromJson(mainObject.getAsJsonObject().get("begin"), Main.class);
Main.setSpot(context,spot);
}
} else {
// Server error exception...
}
return first(context);
}
public static List<Main> first(Context context) {
if (first == null) {
try {
first = new ArrayList<Main>();
} finally {
if (first == null) {
first = new ArrayList<Main>();
}
}
}
return first;
}
public static void setMain(Context context, Main second) {
Main previous = find(context, second.getId());
if (previous != null) {
first.set(first.indexOf(previous), second);
} else {
first = first(context);
first.add(second);
}
}
public static Main find(Context context, String id) {
for(Main first : first(context)) {
if(second.getId().equals(id)) {
return second;
}
}
return null;
}
}
activities/Home.java
public class Home extends Fragment {
private GetMainListTask mGetMainListTask = null;
private ListView mMainListView;
private MainListAdapter mMainListAdapter;
private List<Main> mFirst;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment, container, false);
mFirst = First.first(mContext);
mMainListView = (ListView) rootView.findViewById(R.id.ListView);
mMainListAdapter = new MainListAdapter();
mMainListView.setAdapter(mMainListAdapter);
getFirst(true);
return rootView;
}
public void getFirst(Boolean showProgressDialog){
if (showProgressDialog) {
mProgressDialog = ProgressDialog.show(mContext, "", "Loading...", true);
}
mGetMainListTask = new GetMainListTask();
mGetMainListTask.execute();
}
public class GetMainListTask extends AsyncTask<Void, Void, List<Main>> {
private List<Exception> exceptions = new ArrayList<Exception>();
#Override
protected List<Main> doInBackground(Void... params) {
try {
return Main.updateMain(Home.this.getApplicationContext());
} catch (ServerErrorException e) {
exceptions.add(e);
return null;
} catch (JSONException e) {
exceptions.add(e);
return null;
} catch (Exception e) {
return null;
}
}
#Override
protected void onPostExecute(final List<Main> first) {
for (Exception e : exceptions) {
// Error...
}
if(first == null && exceptions.isEmpty()) {
if (getApplicationContext() != null) {
// Error...
}
}
onGetMainResult(first);
}
}
public void onGetMainResult(List<Main> first) {
boolean worked = (first != null && first.size() != 0);
mGetMainListTask = null;
if (worked) {
mFirst = first;
if (mMainListAdapter != null) {
mMainListAdapter.notifyDataSetChanged();
}
}
}
public class MainListAdapter extends BaseAdapter {
#Override
public int getCount() {
return mFirst.size();
}
#Override
public Object getItem(int i) {
return mFirst.get(i);
}
#Override
public long getItemId(int i) {
return i;
}
#Override
public View getView(int i, View convertView, ViewGroup parent) {
View view = View.inflate(getApplicationContext(), R.layout.list, null);
final Main first = mFirst.get(i);
if (mContext != null && first != null) {
// Do stuff...
}
return view;
}
}
It looks to me like you are trying to use Gson in a way too complicated way.
(Also, what are JSONParse and JSONObject in your code? From org.json or Jackson apparently. Why on earth would you use several different JSON libraries in the same piece of code? Just stick to Gson!)
If we begin with your original JSON string:
{ "begin":
[
{"id":1,"name":"1","size":2},
{"id":2,"name":"2","size":2}],
"end":
[
{"id":1,"name":"1","size":2},
{"id":2,"name":"2","size":2}
]
}
A natural way to model that into Java objects would be something like this, using two classes:
public class TopLevel {
List<Main> begin;
List<Main> end;
}
public class Main {
String id;
String name;
}
(Feel free to rename "TopLevel" to something better, to whatever it represents in your application.)
Now, parsing the JSON into Java objects (one TopLevel object containing a total of 4 Main objects), is as simple as:
Gson gson = new GsonBuilder().create();
TopLevel topLevel = gson.fromJson(jsonString, TopLevel.class);
Related
i have a problem which is making me crazy.
i know how to use "SharedPreferences" in android but i dont know where to put it in my project,like onCreate(),onDestroy() or somewhere else.
*i want to save NoteLab.mNotes in NoteListFragment
*Note.java
package notes.com.example.alireza;
public class Note {
public UUID nId;
public Date nDate;
public String nTitle;
public String nDetails;
public Note(){
nId = UUID.randomUUID();
nDate = new Date();
}
public Date getnDate(){
return nDate;
}
public UUID getnUUID(){
return nId;
}
public String getnTitle() {
return nTitle;
}
public void setnTitle(String nTitle) {
this.nTitle = nTitle;
}
public String getnDetails() {
return nDetails;
}
public void setnDetails(String nDetails) {
this.nDetails = nDetails;
}
}
*NoteLab.java
package notes.com.example.alireza;
import android.content.Context;
import java.util.ArrayList;
import java.util.UUID;
class NoteLab {
public static ArrayList<Note> mNotes;
public static NoteLab noteLab;
public Context mAppContext;
private NoteLab(Context AppContext){
mAppContext = AppContext;
mNotes = new ArrayList<Note>();
}
public static NoteLab get(Context context){
if (noteLab == null){
noteLab = new NoteLab(context.getApplicationContext());
}
return noteLab;
}
public static ArrayList<Note> getNotes(){
return mNotes;
}
public static Note getNote(UUID mId){
for (Note n: mNotes){
if (mId == n.getnUUID()){
return n;
}
}
return null;
}
}
*NoteListFragment.java
package notes.com.example.alireza;
public class NoteListFragment extends ListFragment {
Note note;
ArrayList<Note> notes;
public static Date date;
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
notes = NoteLab.get(getActivity()).getNotes();
myArrayAdapter arrayAdapter = new myArrayAdapter(notes);
setListAdapter(arrayAdapter);
}
#Override
public void onStart() {
super.onStart();
View emptyView = getActivity().getLayoutInflater().inflate(R.layout.emptymainlist,null);
((ViewGroup)getListView().getParent()).addView(emptyView);
getListView().setEmptyView(emptyView);
}
#Override
public void onListItemClick(ListView l, View v, int position, long id) {
int checked = 1;
Note c = ((myArrayAdapter)getListAdapter()).getItem(position);
Intent i = new Intent(getActivity(),NoteActivity.class);
i.putExtra("id",c.getnUUID());
i.putExtra(NoteListActivity.EXTRA_DATE,checked);
startActivity(i);
}
//custom arrayList
public class myArrayAdapter extends ArrayAdapter<Note> {
public myArrayAdapter(ArrayList<Note> notes) {
super(getActivity(), 0, notes);
}
#SuppressLint("SetTextI18n")
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
convertView = getActivity().getLayoutInflater().inflate(R.layout.notelistfragment_item, null);
}
Note n = getItem(position);
date = n.getnDate();
PersianCalendar persianCalendar = new PersianCalendar();
persianCalendar.setTime(date);
TextView titleTextView = convertView.findViewById(R.id.titleTextView);
titleTextView.setText(n.getnTitle());
TextView detailTextView = convertView.findViewById(R.id.detailsTextView);
detailTextView.setText(n.getnDetails());
TextView dateTextView = convertView.findViewById(R.id.dateTextView);
dateTextView.setText(DateFormat.getDateInstance(DateFormat.FULL).format(date) + " : تاریخ ذخیره ");
return convertView;
}
}
#Override
public void onResume() {
super.onResume();
((myArrayAdapter)getListAdapter()).notifyDataSetChanged();
}
as you understand from the codes, i want to save my mNotes arrayList which is placed in NoteLab.java.there is NoteListActivtiy.java too which is supporting NoteListFragment but i think this can be done in NoteListFragment.
thanks to stackoverflow and everyone who tryes to help me.
You can use Gson library to convert what you want to String then you can get it back again.
Where should you put your code ?? it depends on your business (or requirements).
If you want to pass your array of items to fragment or another activity you can use Gson lib to convert it to string then put it into bundle and pass this bundle to whatever you want. Then in the fragment or the activity you can get this array by Gson also.
Here is an example:
Gson gson = new Gson();
gson.toSring(yourData);
// then you can get the data by
Gson gson = new Gson();
String data = yourBundle.getString("your_key");
yourDataModel = gson.fromJson(data, YourDataModel.class);
// it will work even with ArrayList
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 4 years ago.
Improve this question
I'm doing some project and I'm stuck ... I'm doing something wrong, probably with AsyncTask and I have no idea what to fix and how .... there is code I have right now.
ReviewData.class
public class ReviewData implements Parcelable {
private String mAuthor, mContent;
public ReviewData(String author, String content) {
this.mAuthor = author;
this.mContent = content;
}
private ReviewData(Parcel in) {
mAuthor = in.readString();
mContent = in.readString();
}
public static final Creator<ReviewData> CREATOR = new Creator<ReviewData>() {
#Override
public ReviewData createFromParcel(Parcel in) {
return new ReviewData(in);
}
#Override
public ReviewData[] newArray(int size) {
return new ReviewData[size];
}
};
//Getter method for review author
public String getAuthor() {
return mAuthor;
}
//Setter method for review author
public void setAuthor(String author) {
this.mAuthor = author;
}
//Getter method for review content
public String getContent() {
return mContent;
}
//Setter method for review content
public void setContent(String content) {
this.mContent = content;
}
#Override
public int describeContents() {
return 0;
}
#Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(mAuthor);
dest.writeString(mContent);
}
}
ReviewAdapter.class
public class ReviewAdapter extends RecyclerView.Adapter<ReviewAdapter.ReviewViewHolder> {
private ArrayList<ReviewData> mReviewList;
private Context mContext;
public ReviewAdapter(Context context, ArrayList<ReviewData> reviewList) {
this.mContext = context;
this.mReviewList = reviewList;
}
#Override
public ReviewViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
mContext = parent.getContext();
View view = LayoutInflater.from(mContext).inflate(R.layout.review_item_list,
parent, false);
view.setFocusable(true);
return new ReviewViewHolder(view);
}
#Override
public void onBindViewHolder(final ReviewViewHolder holder, int position) {
if(mReviewList != null) {
ReviewData reviewData = mReviewList.get(position);
holder.reviewAuthor.setText(reviewData.getAuthor());
holder.reviewContent.setText(reviewData.getContent());
}
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public int getItemCount() {
if(mReviewList == null) {
return 0;
} else {
return mReviewList.size();
}
}
public void setReviewList(ArrayList<ReviewData> reviewList) {
if(reviewList != null) {
mReviewList = new ArrayList<>(reviewList);
}
notifyDataSetChanged();
}
public class ReviewViewHolder extends RecyclerView.ViewHolder {
TextView reviewAuthor;
TextView reviewContent;
public ReviewViewHolder(View itemView) {
super(itemView);
reviewAuthor = itemView.findViewById(R.id.review_author);
reviewContent = itemView.findViewById(R.id.review_content);
}
}
}
NetworkUtils.class (but only code for Review url builder, for other thing works perfectly). PS. this parse is written as API documentation said ... it should be someurl/movie/{id}/reviews
//URL builder for reviews
public static URL buildReviewUrl(String id) {
Uri builtUri = Uri.parse(BASE_MOVIE_URL + id + REVIEW).buildUpon()
.appendQueryParameter(QUERY_API_KEY, API_KEY)
.build();
URL url = null;
try {
url = new URL(builtUri.toString());
} catch (MalformedURLException e) {
e.printStackTrace();
}
return url;
}
JsonData. class (also, only for Reviews, for other works perfectly...)
//JSON for Review
public static ArrayList<ReviewData> getReviewFromJson(String json) throws JSONException {
ArrayList<ReviewData> listOfReviews = new ArrayList<>();
try {
JSONObject reviews = new JSONObject(json);
JSONArray reviewsArray = reviews.getJSONArray(QUERY_RESULTS);
for(int i = 0; i < reviewsArray.length(); i++) {
JSONObject jsonReview = reviewsArray.getJSONObject(i);
String author = jsonReview.optString(REVIEW_AUTHOR);
String content = jsonReview.optString(REVIEW_CONTENT);
ReviewData reviewData = new ReviewData(author, content);
listOfReviews.add(reviewData);
}
} catch(JSONException e) {
e.printStackTrace();
Log.e("ReviewJson", "JSON Review Error");
}
return listOfReviews;
}
ReviewAsyncTask.class
public class ReviewAsyncTask extends AsyncTask<String, Void, ArrayList<ReviewData>> {
private ReviewData mReviewData;
public interface ReviewResponse {
void finished(ArrayList<ReviewData> output);
}
private ReviewResponse reviewResponse = null;
public ReviewAsyncTask(ReviewResponse reviewResponse) {
this.reviewResponse = reviewResponse;
}
#Override
protected ArrayList<ReviewData> doInBackground(String... strings) {
String rawData = "";
ArrayList<ReviewData> reviewList = new ArrayList<>();
try {
rawData = NetworkUtils.getResponseFromHttpRequest(NetworkUtils
.buildReviewUrl(String.valueOf(mReviewData)));
reviewList = JsonData.getReviewFromJson(rawData);
} catch (IOException e) {
e.printStackTrace();
Log.e("ReviewAsyncTask", "Error in ReviewAsyncTask");
} catch (JSONException e) {
e.printStackTrace();
Log.e("JSONAsync", "JSON problem");
}
return reviewList;
}
#Override
protected void onPostExecute(ArrayList<ReviewData> reviewData) {
reviewResponse.finished(reviewData);
}
}
and MovieDetails activity (everything works fine except from the comment recycle review to next comment.
public class MovieDetails extends AppCompatActivity implements ReviewAsyncTask.ReviewResponse {
private final static String BASE_URL = "http://image.tmdb.org/t/p/";
private final static String SIZE = "w185/";
private ArrayList<ReviewData> mReviewList;
private ReviewAdapter mReviewAdapter;
#BindView(R.id.poster_detail)
ImageView mMoviePoster;
#BindView(R.id.title_detail)
TextView mMovieTitle;
#BindView(R.id.release_date)
TextView mReleaseDate;
#BindView(R.id.average_vote)
TextView mAverageVote;
#BindView(R.id.synopsis)
TextView mSynopsis;
#BindView(R.id.review_recycler)
RecyclerView mReviewRecycle;
Context mContext;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_movie_details);
ButterKnife.bind(this);
displayMovieDetail();
//Review RecycleView
mReviewList = new ArrayList<>();
mReviewAdapter = new ReviewAdapter(this, mReviewList);
RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(this);
mReviewRecycle.setLayoutManager(layoutManager);
mReviewRecycle.setHasFixedSize(true);
mReviewRecycle.setAdapter(mReviewAdapter);
}
#Override
public void finished(ArrayList<ReviewData> output) {
ReviewAsyncTask reviewAsyncTask = new ReviewAsyncTask(this);
reviewAsyncTask.execute();
}
/* Method for displaying the info about movies in activity details
* #param mMoviePoster sets the movie poster
* #param mMovieTitle sets original title of the movie
* #param mReleaseDate sets release date of the movie
* #param mAverageVote sets average rating grade of the movie
* #param mSynopsis sets plot of the movie */
private void displayMovieDetail() {
int idMovie = (Integer) getIntent().getExtras().get(getString(R.string.movie_id));
List<MovieData> movieList;
movieList = getIntent().getParcelableArrayListExtra(getString(R.string.movie_lsit));
MovieData movieData = movieList.get(idMovie);
Picasso.with(mContext).load(BASE_URL + SIZE +
movieData.getPoster()).into(mMoviePoster);
mMovieTitle.setText(movieData.getTitle());
mReleaseDate.setText(movieData.getReleaseDate());
mAverageVote.setText(Double.toString(movieData.getRating()));
mSynopsis.setText(movieData.getSynopsis());
}
}
P.S. I would share github link but I should give you my personal API key. :(
You need to start the AsyncTask in onCreate() (like you did before) and in finished() you take the results and add them to the Adapter's data list.
Finally, don't forget to call notifyDatasetChanged().
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_movie_details);
// skipping some lines of code here...
mReviewRecycle.setAdapter(mReviewAdapter);
ReviewAsyncTask reviewAsyncTask = new ReviewAsyncTask(this);
reviewAsyncTask.execute();
}
#Override
public void finished(ArrayList<ReviewData> output) {
mReviewList.addAll(output);
mReviewAdapter.notifyDatasetChanged();
}
(Please note that I skipped null checks and error handling for brevity's sake)
In MovieDetails onCreate retrieve current movie ID like you do in displayMovieDetail.
Send that ID to ReviewAsyncTask (you'll need to modify constructor of ReviewAsyncTask)
Retrieve id in ReviewAsyncTask, save it as member variable, and then in doInBackground method send that id to buildReviewUrl as an argument.
i have three Generic Classes of list
1 List< Board >
2 List< Class >
3 List< Subject >
during run time i can return any type of list how would i get particular list and display it?
#Override
public Loader<List<Board>> onCreateLoader(int id, Bundle args) {
String s=null;
if (args!=null)
s = args.getString("string_board_id");
if (id==1) {
return new BoardLoader(this, boardUrl);
}
if (id==2){
return new ClassLoader(this, boardUrl,s);
}
return null;
}
#Override
public void onLoadFinished(Loader<List<Board>> loader, List<Board> data) {
if (data !=null && data.size() != 0){
boardAdapter.addAll(data);
}
else{
Log.e(LOG_TAG,"problem with board list ");
}
}
thanks in advance.
Instead of implementing 3 callbacks on Activity, make 3 LoaderManager.LoaderCallbacks<Type> objects. Use these objects when instad of reference to activity.
Use loader.getId() inside onLoadFinished() to see which loader finished in case you want to use a loader callback with 2 loaders.
Something like this:
LoaderManager.LoaderCallbacks<String> mStringCallbacks = new LoaderManager.LoaderCallbacks<String>() {
#Override
public Loader<String> onCreateLoader(int id, Bundle args) {
return null;
}
#Override
public void onLoadFinished(Loader<String> loader, String data) {
}
#Override
public void onLoaderReset(Loader<String> loader) {
}
};
this is my Home Activity
package com.directionclasses.directionclasses;
import android.app.LoaderManager;
import android.content.Loader;
import android.os.Build;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Spinner;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.List;
public class HomeActivity extends AppCompatActivity implements LoaderManager.LoaderCallbacks<List<Object>> {
public static final String LOG_TAG = HomeActivity.class.getName();
Spinner spinner;
Spinner spinnerClass;
Spinner spinnerSubject;
private static final int mBoardLoaderManager=1;
private static final int mClassLoaderManager=2;
private static final int mSubjectLoaderManager=3;
private static final String boardUrl = "http://directionclasses.com/Android/selectBoard.php";
private static final String classUrl = "http://directionclasses.com/Android/selectClass.php";
private static final String subjectUrl = "http://directionclasses.com/Android/selectSubject.php";
BoardAdapter boardAdapter = null;
ClassAdapter classAdapter = null;
SubjectAdapter subjectAdapter = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
Toolbar mToolBar=(Toolbar)findViewById(R.id.toolbar);
mToolBar.setTitle(getString(R.string.app_name));
// mToolBar.setNavigationIcon(R.drawable.ic_launcher);
mToolBar.inflateMenu(R.menu.menu_main);
android.app.LoaderManager loaderManager=getLoaderManager();
loaderManager.initLoader(mBoardLoaderManager,null,this);
spinner = (Spinner) findViewById(R.id.spinner1);
spinnerClass = (Spinner) findViewById(R.id.spinner2);
spinnerSubject = (Spinner) findViewById(R.id.spinner3);
boardAdapter = new BoardAdapter(this, new ArrayList<Board>());
classAdapter = new ClassAdapter(this, new ArrayList<Class>());
subjectAdapter = new SubjectAdapter(this, new ArrayList<Subject>());
spinner.setAdapter(boardAdapter);
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
Board board = boardAdapter.getItem(position);
int board_id = board.getBoard_id();
if (board_id != 0) {
Toast.makeText(HomeActivity.this, "jai ho" + board_id, Toast.LENGTH_SHORT).show();
String string_board_id = String.valueOf(board_id);
Bundle b = new Bundle();
b.putString("string_board_id", string_board_id);
android.app.LoaderManager loaderManager=getLoaderManager();
loaderManager.initLoader(mClassLoaderManager,b,HomeActivity.this);
} else {
Toast.makeText(HomeActivity.this, "jai ho with no id", Toast.LENGTH_SHORT).show();
}
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
}
#Override
public Loader<List<Object>> onCreateLoader(int id, Bundle args) {
String s=null;
if (args!=null) {
s = args.getString("string_board_id");
}
if (id==1) {
return new BoardLoader(this, boardUrl);
}
if (id==2){
return new ClassLoader(this, classUrl,s);
}
return null;
}
#Override
public void onLoadFinished(Loader<List<Object>> loader, List<Object> data) {
int loader_id=loader.getId();
if (loader_id==1){
if (data !=null && data.size() != 0){
List<Board> mythings = (List<Board>) (Object) data;
boardAdapter.addAll(mythings);
}
else{
Log.e(LOG_TAG,"problem with board list ");
}
}
if (loader_id==2){
if (data !=null && data.size() != 0){
List<Class> mythings = (List<Class>) (Object) data;
classAdapter.addAll(mythings);
}
else{
Log.e(LOG_TAG,"problem with class list ");
}
}
if (loader_id==3){
if (data !=null && data.size() != 0){
List<Subject> mythings = (List<Subject>) (Object) data;
subjectAdapter.addAll(mythings);
}
else{
Log.e(LOG_TAG,"problem with subject list ");
}
}
}
#Override
public void onLoaderReset(Loader<List<Object>> loader) {
Log.v(LOG_TAG,"this is the on Load Reset method");
// boardAdapter.clear();
}
}
this is my BoardLoader.java file
package com.directionclasses.directionclasses;
import android.content.AsyncTaskLoader;
import android.content.Context;
import android.util.Log;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.List;
public class BoardLoader extends AsyncTaskLoader {
private static final String LOG_TAG = BoardLoader.class.getName();
private String mUrl;
public BoardLoader(Context context, String url) {
super(context);
mUrl = url;
}
#Override
public List<Board> loadInBackground() {
ArrayList<Board> boards1 = new ArrayList<Board>();
URL url1 = null;
try {
url1 = new URL(mUrl);
} catch (MalformedURLException e) {
e.printStackTrace();
Log.e(LOG_TAG, "this is url malformed exception");
}
BufferedReader reader = null;
String text = null;
try {
URLConnection conn = url1.openConnection();
conn.setDoOutput(true);
OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
wr.flush();
reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
text = sb.toString();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
boards1 = featuresExtractFromJson(text);
return boards1;
}
#Override
protected void onStartLoading() {
forceLoad();
}
private ArrayList<Board> featuresExtractFromJson(String JsonResponse) {
ArrayList<Board> results = new ArrayList<Board>();
try {
JSONArray root = new JSONArray(JsonResponse);
for (int i = 0; i < root.length(); i++) {
JSONObject jsonObject = root.getJSONObject(i);
String board_id = jsonObject.getString("board_id");
String board_name = jsonObject.getString("board_name");
int parse_board_id = Integer.parseInt(board_id);
results.add(new Board(parse_board_id, board_name));
}
} catch (JSONException e) {
e.printStackTrace();
Log.e(LOG_TAG, "Json execption");
}
return results;
}
}
this is my Board Adapter.java File
public class BoardAdapter extends ArrayAdapter<Board> {
public BoardAdapter(Context context, ArrayList<Board> boards) {
super(context, 0, boards);
}
public BoardAdapter(#NonNull Context context, #LayoutRes int resource, ArrayList<Board> boards) {
super(context, resource);
}
#NonNull
#Override
public View getView(int position, #Nullable View convertView, #NonNull ViewGroup parent) {
return getCustomView(position, convertView, parent);
}
#Override
public View getDropDownView(int position, #Nullable View convertView, #NonNull ViewGroup parent) {
return getCustomView(position, convertView, parent);
}
public View getCustomView(int position, View convertView, ViewGroup parent) {
View listItemView = convertView;
if (listItemView == null) {
listItemView = LayoutInflater.from(getContext()).inflate(R.layout.row, parent, false);
}
Board board = getItem(position);
int board_id = board.getBoard_id();
String board_name = board.getBoard_name();
TextView text_name = (TextView) listItemView.findViewById(R.id.tv1);
text_name.setText(board_name);
// TextView text_id = (TextView) listItemView.findViewById(R.id.tv2);
// text_id.setText(board_id+"");
return listItemView;
}
}
This is my ClassLoader.java File
public class ClassLoader extends AsyncTaskLoader {
private static final String LOG_TAG = ClassLoader.class.getName();
private String mUrl;
private String borad_id=null;
public ClassLoader(Context context, String url,String borad_id1 ) {
super(context);
mUrl = url;
borad_id=borad_id1;
}
#Override
public Object loadInBackground() {
String data = null;
try {
data = URLEncoder.encode("board_id", "UTF-8") + "=" + URLEncoder.encode(borad_id, "UTF-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
ArrayList<Class> boards1 = new ArrayList<Class>();
URL url1 = null;
try {
url1 = new URL(mUrl);
} catch (MalformedURLException e) {
e.printStackTrace();
Log.e(LOG_TAG, "this is url malformed exception");
}
BufferedReader reader = null;
String text = null;
try {
URLConnection conn = url1.openConnection();
conn.setDoOutput(true);
OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
wr.write(data);
wr.flush();
reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
text = sb.toString();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
boards1 = featuresExtractFromJson(text);
return boards1;
}
#Override
protected void onStartLoading() {
forceLoad();
}
private ArrayList<Class> featuresExtractFromJson(String JsonResponse) {
ArrayList<Class> results = new ArrayList<Class>();
try {
JSONArray root = new JSONArray(JsonResponse);
for (int i = 0; i < root.length(); i++) {
JSONObject jsonObject = root.getJSONObject(i);
String calss_id = jsonObject.getString("calss_id");
String class_name = jsonObject.getString("class_name");
String board_id = jsonObject.getString("board_id");
int parse_board_id = Integer.parseInt(board_id);
int parse_class_id = Integer.parseInt(calss_id);
results.add(new Class(parse_class_id, class_name, parse_board_id));
}
} catch (JSONException e) {
e.printStackTrace();
Log.e(LOG_TAG, "Json execption");
}
return results;
}
}
This is my ClassAdapter.java file
public class ClassAdapter extends ArrayAdapter<Class> {
public static final String LOG_TAG = ClassAdapter.class.getName();
public ClassAdapter(Context context, ArrayList<Class> classes) {
super(context, 0, classes);
}
#NonNull
#Override
public View getView(int position, #Nullable View convertView, #NonNull ViewGroup parent) {
return getCustomView(position, convertView, parent);
}
#Override
public View getDropDownView(int position, #Nullable View convertView, #NonNull ViewGroup parent) {
return getCustomView(position, convertView, parent);
}
public View getCustomView(int position, View convertView, ViewGroup parent) {
View listItemView = convertView;
if (listItemView == null) {
listItemView = LayoutInflater.from(getContext()).inflate(R.layout.row, parent, false);
}
Class classes = getItem(position);
int class_id = classes.getClass_id();
String class_name = classes.getClass_name();
Log.e(LOG_TAG,"string class_name"+class_name);
TextView text_name = (TextView) listItemView.findViewById(R.id.tv1);
text_name.setText(class_name);
// TextView text_id = (TextView) listItemView.findViewById(R.id.tv2);
// text_id.setText(board_id+"");
return listItemView;
}
}
after this code my board value is coming from sever.u can see in the link below
enter image description here
but oniteemclick my class value is fetching respective to its board it from server i have seen them by debugging my application. but my clas value is not displaying in my class spinner.
It appears that the whole inmobi sdk has changed significantly from 4.4.1 to 5.2.3 which means that I cannot integrate the inmobi sdk successfully into mopub. This is adapter bundled within the mopub sdk:
https://github.com/motain/android-ads-MoPub/blob/master/extras/src/com/mopub/nativeads/InMobiNative.java
I have copied and pasted the code here for your convenience - you can see that the author has said that the adapter was tested on 4.4.1:
package com.mopub.nativeads;
import android.app.Activity;
import android.content.Context;
import android.view.View;
import android.view.ViewGroup;
import com.inmobi.commons.InMobi;
import com.inmobi.monetization.IMErrorCode;
import com.inmobi.monetization.IMNative;
import com.inmobi.monetization.IMNativeListener;
import com.mopub.common.util.MoPubLog;
import org.json.JSONException;
import org.json.JSONObject;
import org.json.JSONTokener;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import static com.mopub.common.util.Json.getJsonValue;
import static com.mopub.common.util.Numbers.parseDouble;
/*
* Tested with InMobi SDK 4.4.1
*/
class InMobiNative extends CustomEventNative implements IMNativeListener {
private static final String APP_ID_KEY = "app_id";
private Context mContext;
private CustomEventNativeListener mCustomEventNativeListener;
// CustomEventNative implementation
#Override
protected void loadNativeAd(final Context context,
final CustomEventNativeListener customEventNativeListener,
final Map<String, Object> localExtras,
final Map<String, String> serverExtras) {
mContext = context;
if (!(context instanceof Activity)) {
customEventNativeListener.onNativeAdFailed(NativeErrorCode.NATIVE_ADAPTER_CONFIGURATION_ERROR);
return;
}
final Activity activity = (Activity) context;
final String appId;
if (extrasAreValid(serverExtras)) {
appId = serverExtras.get(APP_ID_KEY);
} else {
customEventNativeListener.onNativeAdFailed(NativeErrorCode.NATIVE_ADAPTER_CONFIGURATION_ERROR);
return;
}
mCustomEventNativeListener = customEventNativeListener;
InMobi.initialize(activity, appId);
final IMNative imNative = new IMNative(this);
imNative.loadAd();
}
// IMNativeListener implementation
#Override
public void onNativeRequestSucceeded(final IMNative imNative) {
if (imNative == null) {
mCustomEventNativeListener.onNativeAdFailed(NativeErrorCode.NETWORK_INVALID_STATE);
return;
}
final InMobiForwardingNativeAd inMobiForwardingNativeAd;
try {
inMobiForwardingNativeAd = new InMobiForwardingNativeAd(imNative);
} catch (IllegalArgumentException e) {
mCustomEventNativeListener.onNativeAdFailed(NativeErrorCode.UNSPECIFIED);
return;
} catch (JSONException e) {
mCustomEventNativeListener.onNativeAdFailed(NativeErrorCode.INVALID_JSON);
return;
}
final List<String> imageUrls = new ArrayList<String>();
final String mainImageUrl = inMobiForwardingNativeAd.getMainImageUrl();
if (mainImageUrl != null) {
imageUrls.add(mainImageUrl);
}
final String iconUrl = inMobiForwardingNativeAd.getIconImageUrl();
if (iconUrl != null) {
imageUrls.add(iconUrl);
}
preCacheImages(mContext, imageUrls, new ImageListener() {
#Override
public void onImagesCached() {
mCustomEventNativeListener.onNativeAdLoaded(inMobiForwardingNativeAd);
}
#Override
public void onImagesFailedToCache(NativeErrorCode errorCode) {
mCustomEventNativeListener.onNativeAdFailed(errorCode);
}
});
}
#Override
public void onNativeRequestFailed(final IMErrorCode errorCode) {
if (errorCode == IMErrorCode.INVALID_REQUEST) {
mCustomEventNativeListener.onNativeAdFailed(NativeErrorCode.NETWORK_INVALID_REQUEST);
} else if (errorCode == IMErrorCode.INTERNAL_ERROR || errorCode == IMErrorCode.NETWORK_ERROR) {
mCustomEventNativeListener.onNativeAdFailed(NativeErrorCode.NETWORK_INVALID_STATE);
} else if (errorCode == IMErrorCode.NO_FILL) {
mCustomEventNativeListener.onNativeAdFailed(NativeErrorCode.NETWORK_NO_FILL);
} else {
mCustomEventNativeListener.onNativeAdFailed(NativeErrorCode.UNSPECIFIED);
}
}
private boolean extrasAreValid(final Map<String, String> serverExtras) {
final String placementId = serverExtras.get(APP_ID_KEY);
return (placementId != null && placementId.length() > 0);
}
static class InMobiForwardingNativeAd extends BaseForwardingNativeAd {
static final int IMPRESSION_MIN_TIME_VIEWED = 0;
// Modifiable keys
static final String TITLE = "title";
static final String DESCRIPTION = "description";
static final String SCREENSHOTS = "screenshots";
static final String ICON = "icon";
static final String LANDING_URL = "landing_url";
static final String CTA = "cta";
static final String RATING = "rating";
// Constant keys
static final String URL = "url";
private final IMNative mImNative;
InMobiForwardingNativeAd(final IMNative imNative) throws IllegalArgumentException, JSONException {
if (imNative == null) {
throw new IllegalArgumentException("InMobi Native Ad cannot be null");
}
mImNative = imNative;
final JSONTokener jsonTokener = new JSONTokener(mImNative.getContent());
final JSONObject jsonObject = new JSONObject(jsonTokener);
setTitle(getJsonValue(jsonObject, TITLE, String.class));
setText(getJsonValue(jsonObject, DESCRIPTION, String.class));
final JSONObject screenShotJsonObject = getJsonValue(jsonObject, SCREENSHOTS, JSONObject.class);
if (screenShotJsonObject != null) {
setMainImageUrl(getJsonValue(screenShotJsonObject, URL, String.class));
}
final JSONObject iconJsonObject = getJsonValue(jsonObject, ICON, JSONObject.class);
if (iconJsonObject != null) {
setIconImageUrl(getJsonValue(iconJsonObject, URL, String.class));
}
setClickDestinationUrl(getJsonValue(jsonObject, LANDING_URL, String.class));
setCallToAction(getJsonValue(jsonObject, CTA, String.class));
try {
setStarRating(parseDouble(jsonObject.opt(RATING)));
} catch (ClassCastException e) {
MoPubLog.d("Unable to set invalid star rating for InMobi Native.");
}
setImpressionMinTimeViewed(IMPRESSION_MIN_TIME_VIEWED);
}
#Override
public void prepareImpression(final View view) {
if (view != null && view instanceof ViewGroup) {
mImNative.attachToView((ViewGroup) view);
} else if (view != null && view.getParent() instanceof ViewGroup) {
mImNative.attachToView((ViewGroup) view.getParent());
} else {
MoPubLog.e("InMobi did not receive ViewGroup to attachToView, unable to record impressions");
}
}
#Override
public void handleClick(final View view) {
mImNative.handleClick(null);
}
#Override
public void destroy() {
mImNative.detachFromView();
}
}
}
Has anyone been successful in converting this adapter to work with the latest 5.2.3 inmobi sdk?
The 4.4.1 sdk is not even available to download anymore and if there is no adapter for 5.2.3, then I'm afraid inmobi integration with in mopub is not possible?
I waited a few days and did not get any response back from Inmobi so I decided to do some investigation myself on how to solve this issue. Eventually I can across this website which had a sample app with SDK 5.0.0 but the class seems to work with SDK 5.2.3 without any problems.
https://support.inmobi.com/monetize/integration/mediation-adapters/mopub-adaptor-android-sdk-integration-guide/#getting-started
I had to read the class and make my own adjustments to the adapter so that it will work - their adapter had issues as they were using deprecated classes. So here is the updated adapter:
package com.mopub.nativeads;
import android.app.Activity;
import android.content.Context;
import android.support.annotation.NonNull;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import com.inmobi.ads.InMobiAdRequestStatus;
import com.inmobi.sdk.InMobiSdk;
import com.mopub.common.MoPub;
import com.mopub.common.logging.MoPubLog;
import org.json.JSONException;
import org.json.JSONObject;
import org.json.JSONTokener;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import static com.mopub.common.util.Json.getJsonValue;
import static com.mopub.common.util.Numbers.parseDouble;
import static com.mopub.nativeads.NativeImageHelper.preCacheImages;
/*
* Tested with InMobi SDK 5.2.3
*/
public class InMobiNative extends CustomEventNative {
private static boolean isAppIntialize = false;
private JSONObject serverParams;
private String accountId="XXX";
private long placementId=123L;
#Override
protected void loadNativeAd(#NonNull Activity arg0,
#NonNull CustomEventNativeListener arg1,
#NonNull Map<String, Object> arg2,
#NonNull Map<String, String> arg3) {
// TODO Auto-generated method stub
Log.d("InMobiNativeCustomEvent", "Reached native adapter");
try {
serverParams = new JSONObject(arg3);
} catch (Exception e) {
Log.e("InMobi", "Could not parse server parameters");
e.printStackTrace();
}
Activity activity = null;
if (arg0 instanceof Activity) {
activity = arg0;
} else {
// You may also pass in an Activity Context in the localExtras map
// and retrieve it here.
}
if (activity == null) {
arg1.onNativeAdFailed(NativeErrorCode.NATIVE_ADAPTER_CONFIGURATION_ERROR);
return;
}
try {
accountId = serverParams.getString("accountid");
placementId = serverParams.getLong("placementId");
} catch (JSONException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
if (!isAppIntialize) {
try {
InMobiSdk.init(activity,"accountid");
} catch (Exception e) {
e.printStackTrace();
}
isAppIntialize = true;
}
InMobiSdk.setAreaCode("areacode");
InMobiSdk.setEducation(InMobiSdk.Education.HIGH_SCHOOL_OR_LESS);
InMobiSdk.setGender(InMobiSdk.Gender.MALE);
InMobiSdk.setIncome(1000);
InMobiSdk.setAge(23);
InMobiSdk.setPostalCode("postalcode");
InMobiSdk.setLogLevel(InMobiSdk.LogLevel.DEBUG);
InMobiSdk.setLocationWithCityStateCountry("blore", "kar", "india");
InMobiSdk.setLanguage("ENG");
InMobiSdk.setInterests("dance");
InMobiSdk.setEthnicity(InMobiSdk.Ethnicity.ASIAN);
InMobiSdk.setYearOfBirth(1980);
Map<String, String> map = new HashMap<String, String>();
map.put("tp", "c_mopub");
map.put("tp-ver", MoPub.SDK_VERSION);
final InMobiStaticNativeAd inMobiStaticNativeAd =
new InMobiStaticNativeAd(arg0,
new ImpressionTracker(arg0),
new NativeClickHandler(arg0),
arg1);
inMobiStaticNativeAd.setIMNative(new com.inmobi.ads.InMobiNative(placementId, inMobiStaticNativeAd));
inMobiStaticNativeAd.setExtras(map);
inMobiStaticNativeAd.loadAd();
}
static class InMobiStaticNativeAd extends StaticNativeAd implements com.inmobi.ads.InMobiNative.NativeAdListener {
static final int IMPRESSION_MIN_TIME_VIEWED = 1000;
// Modifiable keys
static final String TITLE = "title";
static final String DESCRIPTION = "description";
static final String SCREENSHOTS = "screenshots";
static final String ICON = "icon";
static final String LANDING_URL = "landingURL";
static final String CTA = "cta";
static final String RATING = "rating";
// Constant keys
static final String URL = "url";
private final Context mContext;
private final CustomEventNativeListener mCustomEventNativeListener;
private final ImpressionTracker mImpressionTracker;
private final NativeClickHandler mNativeClickHandler;
private com.inmobi.ads.InMobiNative mImNative;
InMobiStaticNativeAd(final Context context,
final ImpressionTracker impressionTracker,
final NativeClickHandler nativeClickHandler,
final CustomEventNativeListener customEventNativeListener) {
InMobiSdk.init(context,"9107a61fcda34c969d3f74934a352dcb");
mContext = context.getApplicationContext();
mImpressionTracker = impressionTracker;
mNativeClickHandler = nativeClickHandler;
mCustomEventNativeListener = customEventNativeListener;
}
void setIMNative(final com.inmobi.ads.InMobiNative imNative) {
mImNative = imNative;
}
void setExtras(Map<String,String> map){
mImNative.setExtras(map);
}
void loadAd() {
mImNative.load();
}
// Lifecycle Handlers
#Override
public void prepare(final View view) {
if (view != null && view instanceof ViewGroup) {
com.inmobi.ads.InMobiNative.bind((ViewGroup)view, mImNative);
} else if (view != null && view.getParent() instanceof ViewGroup) {
com.inmobi.ads.InMobiNative.bind((ViewGroup)(view.getParent()), mImNative);
} else {
Log.e("MoPub", "InMobi did not receive ViewGroup to attachToView, unable to record impressions");
}
mImpressionTracker.addView(view, this);
mNativeClickHandler.setOnClickListener(view, this);
}
#Override
public void clear(final View view) {
mImpressionTracker.removeView(view);
mNativeClickHandler.clearOnClickListener(view);
}
#Override
public void destroy() {
//InMobiNative.unbind(arg0);
mImpressionTracker.destroy();
}
// Event Handlers
#Override
public void recordImpression(final View view) {
notifyAdImpressed();
}
#Override
public void handleClick(final View view) {
notifyAdClicked();
mNativeClickHandler.openClickDestinationUrl(getClickDestinationUrl(), view);
mImNative.reportAdClick(null);
}
void parseJson(final com.inmobi.ads.InMobiNative inMobiNative) throws JSONException {
final JSONTokener jsonTokener = new JSONTokener((String) inMobiNative.getAdContent());
final JSONObject jsonObject = new JSONObject(jsonTokener);
setTitle(getJsonValue(jsonObject, TITLE, String.class));
String text = getJsonValue(jsonObject, DESCRIPTION, String.class);
if(text!=null)
setText(text);
final JSONObject screenShotJsonObject = getJsonValue(jsonObject, SCREENSHOTS, JSONObject.class);
if (screenShotJsonObject != null) {
setMainImageUrl(getJsonValue(screenShotJsonObject, URL, String.class));
}
final JSONObject iconJsonObject = getJsonValue(jsonObject, ICON, JSONObject.class);
if (iconJsonObject != null) {
setIconImageUrl(getJsonValue(iconJsonObject, URL, String.class));
}
final String clickDestinationUrl = getJsonValue(jsonObject, LANDING_URL, String.class);
if (clickDestinationUrl == null) {
final String errorMessage = "InMobi JSON response missing required key: "
+ LANDING_URL + ". Failing over.";
MoPubLog.d(errorMessage);
throw new JSONException(errorMessage);
}
setClickDestinationUrl(clickDestinationUrl);
String cta = getJsonValue(jsonObject, CTA, String.class);
if(cta!=null)
setCallToAction(cta);
try {
if(jsonObject.opt(RATING)!=null){
setStarRating(parseDouble(jsonObject.opt(RATING)));
}
} catch (ClassCastException e) {
Log.d("MoPub", "Unable to set invalid star rating for InMobi Native.");
} setImpressionMinTimeViewed(IMPRESSION_MIN_TIME_VIEWED);
}
#Override
public void onAdDismissed(com.inmobi.ads.InMobiNative inMobiNative) {
// TODO Auto-generated method stub
Log.d("InMobiNativeCustomEvent","Native Ad is dismissed");
}
#Override
public void onAdDisplayed(com.inmobi.ads.InMobiNative inMobiNative) {
// TODO Auto-generated method stub
Log.d("InMobiNativeCustomEvent","Native Ad is displayed");
}
#Override
public void onAdLoadFailed(com.inmobi.ads.InMobiNative arg0, InMobiAdRequestStatus arg1) {
// TODO Auto-generated method stub
Log.d("InMobiNativeCustomEvent","Native ad failed to load");
String errorMsg="";
switch (arg1.getStatusCode()) {
case INTERNAL_ERROR:
errorMsg="INTERNAL_ERROR";
break;
case REQUEST_INVALID:
errorMsg="INVALID_REQUEST";
break;
case NETWORK_UNREACHABLE:
errorMsg="NETWORK_UNREACHABLE";
break;
case NO_FILL:
errorMsg="NO_FILL";
break;
case REQUEST_PENDING:
errorMsg="REQUEST_PENDING";
break;
case REQUEST_TIMED_OUT:
errorMsg="REQUEST_TIMED_OUT";
break;
case SERVER_ERROR:
errorMsg="SERVER_ERROR";
break;
case AD_ACTIVE:
errorMsg="AD_ACTIVE";
break;
case EARLY_REFRESH_REQUEST:
errorMsg="EARLY_REFRESH_REQUEST";
break;
default:
errorMsg="NETWORK_ERROR";
break;
}
if (errorMsg == "INVALID_REQUEST") {
mCustomEventNativeListener.onNativeAdFailed(NativeErrorCode.NETWORK_INVALID_REQUEST);
} else if (errorMsg == "INTERNAL_ERROR" || errorMsg == "NETWORK_ERROR") {
mCustomEventNativeListener.onNativeAdFailed(NativeErrorCode.NETWORK_INVALID_STATE);
} else if (errorMsg == "NO_FILL") {
mCustomEventNativeListener.onNativeAdFailed(NativeErrorCode.NETWORK_NO_FILL);
} else if (errorMsg == "REQUEST_TIMED_OUT"){
mCustomEventNativeListener.onNativeAdFailed(NativeErrorCode.NETWORK_TIMEOUT);
}else if(errorMsg == "NETWORK_UNREACHABLE"){
mCustomEventNativeListener.onNativeAdFailed(NativeErrorCode.CONNECTION_ERROR);
}
else {
mCustomEventNativeListener.onNativeAdFailed(NativeErrorCode.UNSPECIFIED);
}
}
#Override
public void onUserLeftApplication(com.inmobi.ads.InMobiNative arg0) {
// TODO Auto-generated method stub
Log.d("InMobiNativeCustomEvent","User left application");
}
#Override
public void onAdLoadSucceeded(com.inmobi.ads.InMobiNative inMobiNative) {
// TODO Auto-generated method stub
Log.v("InMobiNativeCustomEvent", "Ad loaded:"+inMobiNative.getAdContent().toString());
try {
parseJson(inMobiNative);
} catch (JSONException e) {
mCustomEventNativeListener.onNativeAdFailed(NativeErrorCode.INVALID_RESPONSE);
return;
}
final List<String> imageUrls = new ArrayList<String>();
/*final String mainImageUrl = getMainImageUrl();
if (mainImageUrl != null) {
imageUrls.add(mainImageUrl);
}*/
final String iconUrl = getIconImageUrl();
if (iconUrl != null) {
imageUrls.add(iconUrl);
}
preCacheImages(mContext, imageUrls, new NativeImageHelper.ImageListener() {
#Override
public void onImagesCached() {
Log.v("InMobiNativeCustomEvent", "image cached");
mCustomEventNativeListener.onNativeAdLoaded(InMobiStaticNativeAd.this);
}
#Override
public void onImagesFailedToCache(NativeErrorCode errorCode) {
Log.v("InMobiNativeCustomEvent", "image failed to cache");
mCustomEventNativeListener.onNativeAdFailed(errorCode);
}
});
}
}
}
Then you need to read this website telling you more about how to integrate their SDK into your app. You need to copy and paste this into your manifest:
https://support.inmobi.com/android-sdk-integration-guide/#getting-started
<activity android:name="com.inmobi.rendering.InMobiAdActivity"
android:configChanges="keyboardHidden|orientation|keyboard|smallestScreenSize|screenSize"
android:theme="#android:style/Theme.Translucent.NoTitleBar"
android:hardwareAccelerated="true" />
<receiver
android:name="com.inmobi.commons.core.utilities.uid.ImIdShareBroadCastReceiver"
android:enabled="true"
android:exported="true" >
<intent-filter>
<action android:name="com.inmobi.share.id" />
</intent-filter>
</receiver>
Without these classes, the SDK will not initialize and you will get an error in the logs.
Please do read through both websites, I'm just dealing on a high level on how you can solve the integration but there are other stuff you should put into your app to make mopub work successfully with inmobi for Android.
I'm new to android development application and i suppose to parse rss url into a listview. the code is working but we want to extract the images from the rss feed and display it into the listview.
RssItem.java
public class RssItem {
// item title
private String title;
// item link
private String link;
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getLink() {
return link;
}
public void setLink(String link) {
this.link = link;
}
#Override
public String toString() {
return title;
}
}
ListListener.java
public class ListListener implements OnItemClickListener {
// List item's reference
List<RssItem> listItems;
// Calling activity reference
Activity activity;
public ListListener(List<RssItem> aListItems, Activity anActivity) {
listItems = aListItems;
activity = anActivity;
}
/**
* Start a browser with url from the rss item.
*/
public void onItemClick(AdapterView<?> parent, View view, int pos, long id) {
Intent i = new Intent(Intent.ACTION_VIEW);
i.setData(Uri.parse(listItems.get(pos).getLink()));
activity.startActivity(i);
}
}
RssParseHandler.java
public class RssParseHandler extends DefaultHandler {
private List<RssItem> rssItems;
// Used to reference item while parsing
private RssItem currentItem;
// Parsing title indicator
private boolean parsingTitle;
// Parsing link indicator
private boolean parsingLink;
public RssParseHandler() {
rssItems = new ArrayList<RssItem>();
}
public List<RssItem> getItems() {
return rssItems;
}
#Override
public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException
{
if ("item".equals(qName)) {
currentItem = new RssItem();
} else if ("title".equals(qName)) {
parsingTitle = true;
} else if ("link".equals(qName)) {
parsingLink = true;
}
}
#Override
public void endElement(String uri, String localName, String qName) throws SAXException {
if ("item".equals(qName)) {
rssItems.add(currentItem);
currentItem = null;
} else if ("title".equals(qName)) {
parsingTitle = false;
} else if ("link".equals(qName)) {
parsingLink = false;
}
}
#Override
public void characters(char[] ch, int start, int length) throws SAXException {
if (parsingTitle) {
if (currentItem != null)
currentItem.setTitle(new String(ch, start, length));
} else if (parsingLink) {
if (currentItem != null) {
currentItem.setLink(new String(ch, start, length));
parsingLink = false;
}
}
}
}
RssReader.java
public class RssReader {
private String rssUrl;
/**
* Constructor
*
* #param rssUrl
*/
public RssReader(String rssUrl) {
this.rssUrl = rssUrl;
}
/**
* Get RSS items.
*
* #return
*/
public List<RssItem> getItems() throws Exception {
// SAX parse RSS data
SAXParserFactory factory = SAXParserFactory.newInstance();
SAXParser saxParser = factory.newSAXParser();
RssParseHandler handler = new RssParseHandler();
saxParser.parse(rssUrl, handler);
return handler.getItems();
}
}
ITCutiesReaderAppActivity.java
public class ITCutiesReaderAppActivity extends Activity {
// A reference to the local object
private ITCutiesReaderAppActivity local;
/**
* This method creates main application view
*/
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Set view
setContentView(R.layout.main);
// Set reference to this activity
local = this;
GetRSSDataTask task = new GetRSSDataTask();
// Start download RSS task
task.execute("http://www.itcuties.com/feed/#sthash.YI6YrEet.dpuf");
// Debug the thread name
Log.d("ITCRssReader", Thread.currentThread().getName());
}
public class GetRSSDataTask extends AsyncTask<String, Void, List<RssItem> > {
#Override
protected List<RssItem> doInBackground(String... urls) {
// Debug the task thread name
Log.d("ITCRssReader", Thread.currentThread().getName());
try {
// Create RSS reader
RssReader rssReader = new RssReader(urls[0]);
// Parse RSS, get items
return rssReader.getItems();
} catch (Exception e) {
Log.e("ITCRssReader", e.getMessage());
}
return null;
}
#Override
protected void onPostExecute(List<RssItem> result) {
// Get a ListView from main view
ListView itcItems = (ListView) findViewById(R.id.listMainView1);
// Create a list adapter
ArrayAdapter<RssItem> adapter = new ArrayAdapter<RssItem> (local,android.R.layout.simple_list_item_1, result);
// Set list adapter for the ListView
itcItems.setAdapter(adapter);
// Set list view item click listener
itcItems.setOnItemClickListener(new ListListener(result, local));
}
}
}
After reading online for a few hours I got this, originally the code didn't parse the image but after reading documentation on DOM elements (from the documentation that comes with Android Studio), I was able to create the following code snippet which actually works. I tested it in a console.
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
/**
* Created by user on 7/1/2016.
*/
public class FeedParser {
// names of the XML tags
static final String PUB_DATE = "pubDate";
static final String LINK = "link";
static final String TITLE = "title";
static final String ITEM = "item";
static final String IMAGE = "media:thumbnail";
static final String AUTHOR = "author";
final URL feedUrl;
public FeedParser(String feedUrl){
try {
this.feedUrl = new URL(feedUrl);
} catch (MalformedURLException e) {
throw new RuntimeException(e);
}
}
public InputStream getInputStream() {
try {
return feedUrl.openConnection().getInputStream();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
public void parse() {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
try {
DocumentBuilder builder = factory.newDocumentBuilder();
Document dom = builder.parse(this.getInputStream());
Element root = dom.getDocumentElement();
NodeList items = root.getElementsByTagName(ITEM);
for (int i=0;i<items.getLength();i++){
Node item = items.item(i);
NodeList properties = item.getChildNodes();
for (int j=0;j<properties.getLength();j++){
Node property = properties.item(j);
String name = property.getNodeName();
if (name.equalsIgnoreCase(TITLE)){
System.out.println(property.getFirstChild().getNodeValue());
} else if (name.equalsIgnoreCase(LINK)){
System.out.println(property.getFirstChild().getNodeValue());
} else if (name.equalsIgnoreCase(AUTHOR)){
StringBuilder text = new StringBuilder();
NodeList chars = property.getChildNodes();
for (int k=0;k<chars.getLength();k++){
text.append(chars.item(k).getNodeValue());
}
System.out.println(text.toString());
} else if (name.equalsIgnoreCase(PUB_DATE)){
System.out.println(property.getFirstChild().getNodeValue());
}
else if (name.equalsIgnoreCase(IMAGE)){
System.out.println(property.getAttributes().getNamedItem("url").getNodeValue());
}
}
}
} catch (Exception e) {
throw new RuntimeException(e);
}
}
public static void main(String[] aeg){
new FeedParser("http://www.pcworld.com/index.rss").parse();
}
}
Though my answer is late i hope it helps someone else
You are reinventing the wheel. You can simplify everything by using the android-rss library with droidQuery (originally posted here):
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();
List<RSSItem> = feed.getItems();
//use this list to update your list adapter, then call the method "getThumbnails()" to get the images associated with the feed item.
}
}));