error error: cannot find symbol class GithubRepoAdapter - java

I'm a beginner to java and android. I'm sure this is a basic question.
I get an error when trying to import a class defined in a file adjacent to the current file. The code is available at https://github.com/morenoh149/HarryLearnsAndroid/blob/master/HttpDemo/app/src/main/java/com/harrymoreno/httpdemo/MainActivity.java#L44
// MainActivity.java
package com.harrymoreno.httpdemo;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.ListView;
import android.widget.Toast;
import java.util.List;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;
import com.harrymoreno.httpdemo.GitHubRepoAdapter;
public class MainActivity extends AppCompatActivity {
private ListView listView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listView = (ListView) findViewById(R.id.pagination_list);
Retrofit.Builder builder = new Retrofit.Builder()
.baseUrl("https://api.github.com/")
.addConverterFactory(GsonConverterFactory.create());
Retrofit retrofit = builder.build();
GithubClient client = retrofit.create(GithubClient.class);
Call<List<GithubRepo>> call = client.reposForUser("morenoh149");
call.enqueue(new Callback<List<GithubRepo>>() {
#Override
public void onResponse(Call<List<GithubRepo>> call, Response<List<GithubRepo>> response) {
List<GithubRepo> repos = response.body();
// error error: cannot find symbol class GithubRepoAdapter
listView.setAdapter(new GithubRepoAdapter(MainActivity.this, repos));
}
#Override
public void onFailure(Call<List<GithubRepo>> call, Throwable t) {
Toast.makeText(MainActivity.this, "error :(", Toast.LENGTH_SHORT).show();
}
});
}
}
and
// GitHubRepoAdapter.java
package com.harrymoreno.httpdemo;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;
import java.util.List;
public class GitHubRepoAdapter extends ArrayAdapter<GithubRepo> {
private Context context;
private List<GithubRepo> values;
public GitHubRepoAdapter(Context context, List<GithubRepo> values) {
super(context, R.layout.list_item_pagination, values);
this.context = context;
this.values = values;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View row = convertView;
if (row == null) {
LayoutInflater inflater =
(LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
row = inflater.inflate(R.layout.list_item_pagination, parent, false);
}
TextView textView = (TextView) row.findViewById(R.id.list_item_pagination_text);
GithubRepo item = values.get(position);
String message = item.getName();
textView.setText(message);
return row;
}
}

You have spelling mistake on that error line.
It should be GitHubRepoAdapter, not GithubRepoAdapter.

Related

Is it possible change the fragment when listview click

I would like to change the fragment when listview item clicked under Bottom navigation activity
But I have not idea how to write the OnClickListener
Anyone can provide some hints or tell me what wrong in this program?
Here is the program
And thank you for spend the time to view my program
Thank you very much
package com.example.campus.ui.campus;
import android.app.Activity;
import android.app.Fragment;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import androidx.appcompat.app.AppCompatActivity;
import com.example.c.MainActivity;
import com.example.c.R;
import com.example.c.database.campus.CampusData;
import com.example.c.ui.campusInformation.CampusInformationActivity;
import com.example.c.ui.campusInformation.CampusInformationFragment;
import java.util.ArrayList;
import java.util.List;
public class CampusListLayoutAdapter extends BaseAdapter {
private LayoutInflater layoutInflater;
private List<CampusData> campusList = new ArrayList<CampusData>();
private int resourceViewID;
private Context context;
private Context mContext;
static class ViewHolder{
LinearLayout llCampusCard;
TextView tvCampusName;
TextView tvCampusAddress;
ImageView ivCampusImage;
}
public CampusListLayoutAdapter(Context c, List<CampusData> campusList){
context = c;
layoutInflater = LayoutInflater.from(c);
this.campusList = campusList;
}
#Override
public int getCount() {
return campusList.size();
}
#Override
public Object getItem(int i) {
return i;
}
#Override
public long getItemId(int i) {
return i;
}
#Override
public View getView(int i, View view, ViewGroup viewGroup) {
mContext = viewGroup.getContext();
ViewHolder holder = new ViewHolder();
view = layoutInflater.inflate(R.layout.listview_campus, null);
if(view != null){
holder.tvCampusName = view.findViewById(R.id.tvCampusName);
holder.tvCampusAddress = view.findViewById(R.id.tvCampusAddress);
holder.ivCampusImage = view.findViewById(R.id.ivCampusImage);
holder.tvCampusName.setText(campusList.get(i).name);
holder.tvCampusAddress.setText(campusList.get(i).address);
String image = campusList.get(i).image;
resourceViewID = context.getResources().getIdentifier(image, "drawable", context.getPackageName());
holder.ivCampusImage.setImageResource(resourceViewID);
view.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
return view;
}else {
return null;
}
}
}
First of all, create an interface in your adapter class.
public interface Callbacks {
void onItemClick(YourObject object, int position); // arguments as per the requirement
}
change your constructor of adapter as
Callbacks callback;
public CampusListLayoutAdapter(Context c, List<CampusData> campusList, Callbacks callback){
.....
this.callback = callback;
}
Now in your onClick() use..
callback.onItemClick(yourClickedItem, position)
then pass an anonymous or simply implement interface in your activity.
adapter = new CampusListLayoutAdapter(context, list, new CampusListLayoutAdapter.Callbacks() {
#Override
public void onItemClick(Alert_bean alert, int position) {
// do what you want here in activity like changing fragment or view updates
}
});

How to inflate another layout inside of another fragment

Hi i tried to inflate my home_items.xml in my application however it doesnt work it just gives me the fragment_home.xml ONLY im wondering how can i fix this? (I can send any part of my code.)
HomeAdapter.java:
package com.example.soulforge.adapter;
import android.content.Context;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import com.bumptech.glide.Glide;
import com.example.soulforge.R;
import com.example.soulforge.model.HomeModel;
import java.util.List;
import java.util.Random;
import de.hdodenhof.circleimageview.CircleImageView;
public class HomeAdapter extends RecyclerView.Adapter<HomeAdapter.HomeHolder>{
private List<HomeModel> list;
Context context;
public HomeAdapter(List<HomeModel> list, Context context) {
this.list = list;
this.context = context;
}
#NonNull
#Override
public HomeHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.home_items, parent, false);
return new HomeHolder(view);
}
#Override
public void onBindViewHolder(#NonNull HomeHolder holder, int position) {
holder.userNameTv.setText(list.get(position).getUserName());
holder.timeTv.setText(""+list.get(position).getTimestamp());
int count = list.get(position).getLikeCount();
if(count ==0){
holder.likeCountTv.setVisibility(View.INVISIBLE);
}else if (count == 1){
holder.likeCountTv.setText(count + " like");
}else{
holder.likeCountTv.setText(count + " likes");
}
holder.descriptionTv.setText(list.get(position).getDescription());
Random random = new Random();
int color = Color.argb(255, random.nextInt(256), random.nextInt(256), random.nextInt(256));
Glide.with(context.getApplicationContext())
.load(list.get(position).getProfileImage())
.placeholder(R.drawable.ic_person)
.timeout(6500)
.into(holder.profileImage);
Glide.with(context.getApplicationContext())
.load(list.get(position).getImageUrl())
.placeholder(new ColorDrawable(color))
.timeout(7000)
.into(holder.imageView);
}
#Override
public int getItemCount() {
return list.size();
}
static class HomeHolder extends RecyclerView.ViewHolder{
private CircleImageView profileImage;
private TextView userNameTv, timeTv, likeCountTv, descriptionTv;
private ImageView imageView;
private ImageButton likeBtn, commentBtn, shareBtn;
public HomeHolder(#NonNull View itemView) {
super(itemView);
profileImage = itemView.findViewById(R.id.profileImage);
imageView = itemView.findViewById(R.id.imageView);
userNameTv = itemView.findViewById(R.id.nameTv);
timeTv = itemView.findViewById(R.id.timeTv);
likeCountTv = itemView.findViewById(R.id.likeCountTv);
likeBtn = itemView.findViewById(R.id.likeBtn);
commentBtn = itemView.findViewById(R.id.commentBtn);
shareBtn = itemView.findViewById(R.id.shareBtn);
descriptionTv = itemView.findViewById(R.id.descTv);
}
}
}
Home.java:
package com.example.soulforge.fragments;
import android.os.Bundle;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.example.soulforge.R;
import com.example.soulforge.adapter.HomeAdapter;
import com.example.soulforge.model.HomeModel;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.firestore.CollectionReference;
import com.google.firebase.firestore.DocumentReference;
import com.google.firebase.firestore.EventListener;
import com.google.firebase.firestore.FirebaseFirestore;
import com.google.firebase.firestore.FirebaseFirestoreException;
import com.google.firebase.firestore.QueryDocumentSnapshot;
import com.google.firebase.firestore.QuerySnapshot;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
public class Home extends Fragment {
private RecyclerView recyclerView;
HomeAdapter adapter;
private List<HomeModel> list;
private FirebaseUser user;
public Home() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_home, container, false);
}
#Override
public void onViewCreated(#NonNull View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
init(view);
list = new ArrayList<>();
adapter = new HomeAdapter(list, getContext());
recyclerView.setAdapter(adapter);
loadDataFromFirestore();
}
private void init(View view) {
Toolbar toolbar = view.findViewById(R.id.toolbar);
if (getActivity() != null)
((AppCompatActivity) getActivity()).setSupportActionBar(toolbar);
recyclerView = view.findViewById(R.id.recyclerView);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
FirebaseAuth auth = FirebaseAuth.getInstance();
user = auth.getCurrentUser();
}
public void loadDataFromFirestore() {
CollectionReference reference = FirebaseFirestore.getInstance().collection("Users")
.document(user.getUid())
.collection("Post Images");
reference.addSnapshotListener(new EventListener<QuerySnapshot>() {
#Override
public void onEvent(#Nullable QuerySnapshot value, #Nullable FirebaseFirestoreException error) {
if (error != null) {
Log.e("Error: ", error.getMessage());
return;
}
if (value == null)
return;
for (QueryDocumentSnapshot snapshot : value) {
if (!snapshot.exists())
return;
HomeModel model = snapshot.toObject(HomeModel.class);
list.add(new HomeModel(
model.getUserName(),
model.getProfileImage(),
model.getImageUrl(),
model.getUid(),
model.getComments(),
model.getDescription(),
model.getId(),
model.getTimestamp(),
model.getLikeCount()
));
}
adapter.notifyDataSetChanged();
}
});
}
}
Any idea how to fix this? I tried to use inflate however it failed to work as shown it is missing the home items xml enter image description here.
Before you say i have cleared and rebuild and all the FAQ ways to fix this
You're updating wrong list instance
Create one method inside adapter
public updateList(List<HomeModel> list) {
this.list = list;
notifyDataSetChanged()
}
And call it like :
reference.addSnapshotListener(new EventListener<QuerySnapshot>() {
#Override
public void onEvent(#Nullable QuerySnapshot value, #Nullable FirebaseFirestoreException error) {
...
adapter.updateList(new HomeModel(
model.getUserName(),
model.getProfileImage(),
model.getImageUrl(),
model.getUid(),
model.getComments(),
model.getDescription(),
model.getId(),
model.getTimestamp(),
model.getLikeCount()
));
}
}
});

CustomAdapter cannot be appllied to Fragment in Android JSON News app

I am creating an News app, am a newbie, Have some errors in MainActivity.Java i couldn't resolve them. Need help!
This is My MainActivity.Java
package com.example.arumugam.newsreader;
import android.app.Activity;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.Volley;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.lang.String;
import java.util.List;
public class MainActivity extends Fragment {
public MainActivity() {
// Required empty public constructor
}
private List<newsItem> newsFeed = new ArrayList<>();
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.activity_main, container, false);
}
#Override
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
getActivity().setTitle("News");
RequestQueue queue = Volley.newRequestQueue(getActivity().getApplicationContext());
JsonObjectRequest newsReq = new JsonObjectRequest(Request.Method.GET,
"https://raw.githubusercontent.com/sumbganesh/temp/master/convertjson.json",
null,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
JSONArray newsItem = response.getJSONArray("newsItems");
for (int i = 0; i < newsItem.length(); i++) {
JSONObject temp = newsItem.getJSONObject(i);
String title = temp.getString("title");
String description = temp.getString("description");
String url = temp.getString("url");
String urlToImage = temp.getString("urlToImage");
newsFeed.add(new newsItem(title, description, url, urlToImage));
}
} catch (JSONException e){
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
queue.add(newsReq);
ArrayAdapter<newsItem> adapter = new customAdapter(newsFeed,getActivity());
ListView newsItems =(ListView) (getActivity().findViewById(R.id.newsItems));
newsItems.setAdapter(adapter);
}
private class customAdapter extends ArrayAdapter<newsItem>{
Activity context;
customAdapter(List<newsItem> newsFeed, Activity context) {
super(getActivity(), R.layout.item, newsFeed);
this.context = context;
}
#NonNull
#Override
public View getView(int position, View convertView, #NonNull ViewGroup parent) {
if (convertView == null){
convertView = getActivity().getLayoutInflater().inflate(R.layout.item, parent, false);
}
newsItem currentItem = newsFeed.get(position);
ImageView newsImage = (ImageView) convertView.findViewById(R.id.leftIco);
TextView newsHeading = (TextView) convertView.findViewById(R.id.heading);
TextView newsDesc = (TextView) convertView.findViewById(R.id.desc);
newsImage.setImageResource(R.mipmap.ic_launcher);
newsHeading.setText(currentItem.getNewsHeading());
newsDesc.setText(String.valueOf((currentItem.getNewsDesc())));
return convertView;
}
}
}
This is my newsItem.java
public class newsItem {
private String newsHeading;
private String newsDesc;
private String newsDescSmall;
private String time;
private String date;
private String url;
private String imageURL;
public newsItem(String newsHeading, String newsDesc, String date, String time) {
this.newsHeading = newsHeading;
this.newsDesc = newsDesc;
this.time = time;
this.date = date;
this.url = url;
this.imageURL = imageURL;
this.newsDescSmall = this.newsDesc.substring(0, 50) + "...";
}
public String getNewsHeading() {
return newsHeading;
}
public String getNewsDesc() {
return newsDesc;
}
public String getNewsDescSmall() {
return newsDescSmall;
}
public String getTime() {
return time;
}
public String getDate() {
return date;
}
public String getUrl() {
return url;
}
public String getImageURL() {
return imageURL;
}
}
This is my item.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="10dp">
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/leftIco"
android:src="#mipmap/ic_launcher"
android:maxHeight="70dp"
android:maxWidth="70dp"
android:adjustViewBounds="true"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Description"
android:lineSpacingExtra="-3dp"
android:id="#+id/desc"
android:layout_alignBottom="#+id/leftIco"
android:layout_alignLeft="#+id/heading"
android:layout_alignStart="#+id/heading" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="16sp"
android:text="Heading Text"
android:textStyle="bold"
android:id="#+id/heading"
android:scrollHorizontally="true"
android:maxLines="1"
android:layout_marginBottom="15dp"
android:ellipsize="end"
android:layout_alignParentTop="true"
android:layout_toRightOf="#+id/leftIco"
android:layout_toEndOf="#+id/leftIco"
android:layout_marginLeft="24dp"
android:layout_marginStart="24dp" />
</RelativeLayout>
The problem i am facing is with this line
ArrayAdapter<newsItem> adapter = new customAdapter(newsFeed,getActivity());
Thank you in advance..
Error on Android Studio
Logcat Error
05-10 19:39:01.191 1232-1318/system_process E/Parcel: Class not found when unmarshalling: com.truecaller.service.MissedCallReminder
java.lang.ClassNotFoundException: com.truecaller.service.MissedCallReminder
at java.lang.Class.classForName(Native Method)
at java.lang.Class.forName(Class.java:400)
at android.os.Parcel.readParcelableCreator(Parcel.java:2508)
at android.os.Parcel.readParcelable(Parcel.java:2462)
at android.os.Parcel.readValue(Parcel.java:2365)
at android.os.Parcel.readArrayMapInternal(Parcel.java:2732)
at android.os.BaseBundle.unparcel(BaseBundle.java:268)
at android.os.Bundle.putAll(Bundle.java:226)
at android.content.Intent.fillIn(Intent.java:8273)
at
com.android.server.am.PendingIntentRecord.sendInner(PendingIntentRecord.java:244)
at com.android.server.am.PendingIntentRecord.sendWithResult(PendingIntentRecord.java:205)
at com.android.server.am.ActivityManagerService.sendIntentSender(ActivityManagerService.java:7305)
at android.app.PendingIntent.send(PendingIntent.java:836)
at com.android.server.AlarmManagerService$DeliveryTracker.deliverLocked(AlarmManagerService.java:3187)
at com.android.server.AlarmManagerService.deliverAlarmsLocked(AlarmManagerService.java:2620)
at com.android.server.AlarmManagerService$AlarmThread.run(AlarmManagerService.java:2741)
Caused by: java.lang.ClassNotFoundException: com.truecaller.service.MissedCallReminder
at java.lang.Class.classForName(Native Method)
at java.lang.BootClassLoader.findClass(ClassLoader.java:1346)
at java.lang.BootClassLoader.loadClass(ClassLoader.java:1406)
at java.lang.ClassLoader.loadClass(ClassLoader.java:312)
at java.lang.Class.classForName(Native Method) 
at java.lang.Class.forName(Class.java:400) 
at android.os.Parcel.readParcelableCreator(Parcel.java:2508) 
at android.os.Parcel.readParcelable(Parcel.java:2462) 
at android.os.Parcel.readValue(Parcel.java:2365) 
at android.os.Parcel.readArrayMapInternal(Parcel.java:2732) 
at android.os.BaseBundle.unparcel(BaseBundle.java:268) 
at android.os.Bundle.putAll(Bundle.java:226) 
at android.content.Intent.fillIn(Intent.java:8273) 
at com.android.server.am.PendingIntentRecord.sendInner(PendingIntentRecord.java:244) 
at com.android.server.am.PendingIntentRecord.sendWithResult(PendingIntentRecord.java:205) 
at com.android.server.am.ActivityManagerService.sendIntentSender(ActivityManagerService.java:7305) 
at android.app.PendingIntent.send(PendingIntent.java:836) 
at com.android.server.AlarmManagerService$DeliveryTracker.deliverLocked(AlarmManagerService.java:3187) 
at com.android.server.AlarmManagerService.deliverAlarmsLocked(AlarmManagerService.java:2620) 
at com.android.server.AlarmManagerService$AlarmThread.run(AlarmManagerService.javat:2741) 
Caused by: java.lang.NoClassDefFoundError: Class not found using the boot class loader; no stack trace available
You should change in customAdapter class
customAdapter(List<newsItem> newsFeed, Context context) {
super(getActivity(), R.layout.item, newsFeed);
this.context = context;
}
and it will work definitely....
i hope this answer help you..
import android.content.Context;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.Volley;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.lang.String;
import java.util.List;
public class MainActivity extends Fragment {
private List<newsItem> newsFeed = new ArrayList<>();
public MainActivity() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view= inflater.inflate(R.layout.activity_main, container, false);
getActivity().setTitle("News");
RequestQueue queue = Volley.newRequestQueue(getActivity().getApplicationContext());
JsonObjectRequest newsReq = new JsonObjectRequest(Request.Method.GET,
"https://raw.githubusercontent.com/sumbganesh/temp/master/convertjson.json",
null,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
JSONArray newsItem = response.getJSONArray("newsItems");
for (int i = 0; i < newsItem.length(); i++) {
JSONObject temp = newsItem.getJSONObject(i);
String title = temp.getString("title");
String description = temp.getString("description");
String url = temp.getString("url");
String urlToImage = temp.getString("urlToImage");
newsFeed.add(new newsItem(title, description, url, urlToImage));
ArrayAdapter<newsItem> adapter = new customAdapter(newsFeed,getActivity());
ListView newsItems =(ListView) (getActivity().findViewById(R.id.newsItems));
newsItems.setAdapter(adapter);
}
} catch (JSONException e){
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
queue.add(newsReq);
return view;
}
private class customAdapter extends ArrayAdapter<newsItem>{
Context context;
customAdapter(List<newsItem> newsFeed, Context context) {
super(getActivity(), R.layout.item, newsFeed);
this.context = context;
}
#NonNull
#Override
public View getView(int position, View convertView, #NonNull ViewGroup parent) {
newsItem currentItem = newsFeed.get(position);
if (convertView == null){
convertView = getActivity().getLayoutInflater().inflate(R.layout.item, parent, false);
}
ImageView newsImage = (ImageView) convertView.findViewById(R.id.leftIco);
TextView newsHeading = (TextView) convertView.findViewById(R.id.heading);
TextView newsDesc = (TextView) convertView.findViewById(R.id.desc);
newsImage.setImageResource(R.mipmap.ic_launcher);
newsHeading.setText(currentItem.getNewsHeading());
newsDesc.setText(String.valueOf((currentItem.getNewsDesc())));
return convertView;
}
}
}
Found the solution finally.
Modified MainActivity.java
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.support.v7.widget.RecyclerView;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.Volley;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.lang.String;
import java.util.List;
import static android.view.LayoutInflater.from;
public class MainActivity extends AppCompatActivity {
private List<newsItem> newsFeed = new ArrayList<>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
engine();
MainActivity.this.setTitle("News");}
private void engine() {
RequestQueue queue = Volley.newRequestQueue(MainActivity.this);
JsonObjectRequest newsReq = new JsonObjectRequest(Request.Method.GET,
"https://raw.githubusercontent.com/sumbganesh/temp/master/convertjson.json",
null,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
JSONArray newsItem = response.getJSONObject("root").getJSONArray("articles");
for (int i = 0; i < newsItem.length(); i++) {
JSONObject temp = newsItem.getJSONObject(i);
String title = temp.getString("title");
String description = temp.getString("description");
String url = temp.getString("url");
String urlToImage = temp.getString("urlToImage");
newsFeed.add(new newsItem(title, description, url, urlToImage));
}
RecyclerView.Adapter adapter = new customAdapter(MainActivity.this,newsFeed);
RecyclerView newsItems =(RecyclerView) findViewById(R.id.newsItems);
LinearLayoutManager llm=new
LinearLayoutManager(MainActivity.this);
newsItems.setLayoutManager(llm);
newsItems.setAdapter(adapter);
} catch (JSONException e){
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
queue.add(newsReq);
}
private class customAdapter extends RecyclerView.Adapter<MyViewHolder> {
private final List<newsItem> newsfeedlist;
public customAdapter(MainActivity mainActivity, List<newsItem> newsFeed) {
this.newsfeedlist= newsFeed;
}
#Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = getLayoutInflater().from(parent.getContext()).inflate(R.layout.item,parent,false);
return new MyViewHolder(view);
}
#Override
public void onBindViewHolder(MyViewHolder holder, int position) {
newsItem items = newsfeedlist.get(position);
holder.newsImage.setImageResource(R.mipmap.ic_launcher);
holder.newsHeading.setText(items.getNewsHeading());
holder.newsDesc.setText(items.getNewsDesc());
}
#Override
public int getItemCount() {
return newsfeedlist.size();
}
}
private class MyViewHolder extends RecyclerView.ViewHolder{
public ImageView newsImage;
public TextView newsHeading;
public TextView newsDesc;
public MyViewHolder(View itemView) {
super(itemView);
newsImage = (ImageView) itemView.findViewById(R.id.leftIco);
newsHeading = (TextView) itemView.findViewById(R.id.heading);
newsDesc = (TextView) itemView.findViewById(R.id.desc);
}
}
}
Changed fragments to Activity and changed ArrayAdapter to Recycler view
Please share your customAdapter code or refer this tutorial
Listview with customadapter
Note: use recylerView in place of the listview for better performance.
Create a volley singleton class.

How to add JSON data to RecyclerView

This is my RecyclerAdapter code:
package com.example.sander.app;
import android.app.Fragment;
import android.os.Bundle;
import android.support.v7.widget.CardView;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import java.util.ArrayList;
/**
* Created by Sander on 6-4-2017.
*/
public class RecycleAdapter extends RecyclerView.Adapter<RecycleAdapter.MyViewHolder> {
private String[] mDataset;
ArrayList<String> ArrayDataset;
public static class MyViewHolder extends RecyclerView.ViewHolder{
public CardView mCardView;
public TextView mTextView;
public MyViewHolder(View v){
super(v);
mCardView = (CardView) v.findViewById(R.id.card_view);
mTextView = (TextView) v.findViewById(R.id.tv_blah);
}
}
public RecycleAdapter(ArrayList<String> names){
ArrayDataset = names;
}
#Override
public RecycleAdapter.MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType){
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.fragment_card_view, parent, false);
MyViewHolder vh = new MyViewHolder(v);
return vh;
}
#Override
public void onBindViewHolder(MyViewHolder holder, int position){
holder.mTextView.setText(ArrayDataset.get(position));
}
#Override
public int getItemCount() { return ArrayDataset.size(); }
}
And this is my Recycler Fragment code:
package com.example.sander.app;
import android.app.Fragment;
import android.os.Bundle;
import android.support.v7.widget.CardView;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.TextView;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.List;
/**
* Created by Sander on 6-4-2017.
*/
public class RecycleFrame extends Fragment {
ArrayList<String> names = new ArrayList<>();
GoogleMaps maps = new GoogleMaps();
public RecycleFrame() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
RequestQueue rq = Volley.newRequestQueue(getActivity().getApplicationContext());
String url= "http://test.dontstealmywag.ga/api/parkgarage.php";
StringRequest stringRequest = new StringRequest(Request.Method.GET, url,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
// Do something with the response
try{
JSONObject o = new JSONObject(response);
JSONArray values=o.getJSONArray("parkgarage");
for ( int i=0; i< values.length(); i++) {
JSONObject jsonObject = values.getJSONObject(i);
names.add(jsonObject.getString("parkgarage_name"));
}
} catch (JSONException ex){}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
// Handle error
}
});
rq.add(stringRequest);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View rootView = inflater.inflate(R.layout.fragment_recycle, container, false);
RecyclerView VRecyclerView = (RecyclerView) rootView.findViewById(R.id.rv_recycler_view);
VRecyclerView.setHasFixedSize(true);
RecycleAdapter adapter = new RecycleAdapter(names);
VRecyclerView.setAdapter(adapter);
LinearLayoutManager llm = new LinearLayoutManager(getActivity());
VRecyclerView.setLayoutManager(llm);
return rootView;
}
}
Now if I'm correct. My data from my API (link can be found in the code), will be added in an ArrayList called "names", but when I run my code my Recyclerview is empty. How do I add my JSON data to the RecyclerView and display it.
(For the record if I try it with String [] {"Example"} it will show a card with "Example")
Thanks in advance

How to show all images in this gallery app?

I'm making a gallery application.
I have the code for that task, but I'd like to show all SD internal storage images. Only I can see a specific folder in my application, I understand why. This is a method that I found on the internet.
MainActivity.java
import android.content.Intent;
import android.os.Bundle;
import android.os.Environment;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.AdapterView;
import android.widget.GridView;
import com.instinctcoder.gridview.R;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends AppCompatActivity {
private GridView gridView;
private GridViewAdapter gridAdapter;
private List<String> imageItems;
private String imagePath="";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//location where photo saved
imagePath = Environment.getExternalStorageDirectory().toString() + "/DCIM/Camera";//I'd like to add more Folders, but it doesn't work
imageItems = new ArrayList<>();
getImages();
gridView = (GridView) findViewById(R.id.gridView);
gridAdapter = new GridViewAdapter(this, R.layout.grid_item, imageItems);
gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
String imagePath = parent.getAdapter().getItem(position).toString();
Intent intent = new Intent(MainActivity.this, DetailActivity.class);
intent.putExtra("imagePath", imagePath);
startActivity(intent);
}
});
gridView.setAdapter(gridAdapter);
}
private List<String> getImages(){
new File(imagePath ).mkdirs();
File fileTarget = new File(imagePath);
File[] files = fileTarget.listFiles();
imageItems.clear();
if (files!=null){
for (File file: files){
imageItems.add(file.getAbsolutePath());
}
}
return imageItems;
}
}
GridViewAdapter.java
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import com.bumptech.glide.Glide;
import com.instinctcoder.gridview.R;
import java.util.ArrayList;
import java.util.List;
public class GridViewAdapter extends ArrayAdapter {
private Context context;
private List<String> data = new ArrayList<String>();
private int resourceId;
private LayoutInflater inflater ;
public GridViewAdapter(Context context, int resourceId, List<String> data) {
super(context, resourceId, data);
this.resourceId = resourceId;
this.context = context;
this.data = data;
inflater = LayoutInflater.from(context);
}
static class ViewHolder {
ImageView image;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View row = convertView;
ViewHolder holder = null;
if (row == null) {
row = inflater.inflate(resourceId, parent, false);
holder = new ViewHolder();
holder.image = (ImageView) row.findViewById(R.id.image);
row.setTag(holder);
} else {
holder = (ViewHolder) row.getTag();
}
Glide.with(context)
.load("file://" + data.get(position))
.fitCenter()
.centerCrop()
.into(holder.image);
return row;
}
Detailactivity.java
package com.instinctcoder.gridview.Galeria;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.widget.ImageView;
import com.bumptech.glide.Glide;
import com.instinctcoder.gridview.R;
public class DetailActivity extends AppCompatActivity {
Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_detail);
String imagePath = getIntent().getStringExtra("imagePath");
ImageView picturesView = (ImageView) findViewById(R.id.image);
Glide.with(DetailActivity.this)
.load("file://" + imagePath)
.fitCenter()
.centerCrop()
.into(picturesView);
}
}
In manifest I have declared permissions storage, parent activity.
Also, I'm add glide library on gradle.

Categories