my app crashes without showing an error - java

I'm working on an app that displays a list of courses form database to the user
my problem is when i try to run my app it crashes without showing errors
I think my problem is at the adapter but i'm not sure
here is my MainActivity.java`
package com.example.android.mycoursesapp;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.widget.CheckBox;
import android.widget.ListView;
import com.google.firebase.database.ChildEventListener;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import java.util.ArrayList;
import java.util.List;
import static com.example.android.mycoursesapp.R.id.checkButton;
public class MainActivity extends AppCompatActivity {
ListView mCourseListView;
CheckBox mCheckBox;
CourseAdapter courseAdapter;
private ChildEventListener mchildEventListener; //to read from the database
private FirebaseDatabase mfirebasedatabase; //to access the database
private DatabaseReference mCoursesDatabaseReference; //references a specific part in the database
private DatabaseReference mMessagesDatabaseReference; //class references a specific part of the database
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Initialize course ListView and its adapter
final List<Course> course = new ArrayList<>();
courseAdapter = new CourseAdapter(this, R.layout.list_item, course);
mCourseListView.setAdapter(courseAdapter);
DatabaseReference mDatabase = FirebaseDatabase.getInstance().getReference();
//get reference to child node
mDatabase.child("courses").push().setValue("Physics");
mDatabase.child("courses").push().setValue("Electronics");
mDatabase.child("courses").push().setValue("System Analysis");
mDatabase.child("courses").push().setValue("Artificial Intelligence");
mDatabase.child("courses").push().setValue("English");
mDatabase.child("courses").push().setValue("Economics");
mchildEventListener=new ChildEventListener() {
#Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
Course course=dataSnapshot.getValue(Course.class);
courseAdapter.add(course);
}
#Override
public void onChildChanged(DataSnapshot dataSnapshot, String s) {}
#Override
public void onChildRemoved(DataSnapshot dataSnapshot) {}
#Override
public void onChildMoved(DataSnapshot dataSnapshot, String s) {}
#Override
public void onCancelled(DatabaseError databaseError) {}
};
mDatabase.addChildEventListener(mchildEventListener);
/*add the Value event listener to update the data in real-time
- displays the friendsDatabase items in a list*/
//addValueEventListener(friendsDatabaseReference);
/*Course course=new Course(listItemTextView.getText.
mMessagesDatabaseReference.push().setValue(course);*/
// Initialize references to views
mCourseListView = (ListView) findViewById(R.id.courseListView);
mCheckBox=(CheckBox) findViewById(checkButton);
//Creating Adapter object for setting to list
/*CourseAdapter adapter=new CourseAdapter(courseList,MainActivity.this);
mCourseListView.setAdapter(adapter);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
R.layout.list_item,
listItemTextView,values);
mCourseListView.setAdapter(adapter);*/
}
}
here is Course.java
package com.example.android.mycoursesapp;
/**
*/
public class Course {
public String courseName;
//private boolean checked;
//private boolean checked = false;
public Course(String courseName) {
this.courseName = courseName;
//this.checked = checked;
}
public String getCourseName() {return courseName;}
public void setCourseName(String courseName) {
this.courseName = courseName;
}
/*public void setChecked(boolean checked) {this.checked = checked;}
public boolean isChecked() {return checked;}*/
/*public boolean isChecked() {
return checked;
}
public void setChecked(boolean checked) {
this.checked = checked;
}*/
}
here is CourseAdapter.java
package com.example.android.mycoursesapp;
import android.app.Activity;
import android.content.Context;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;
import java.util.List;
/**
*/
public class CourseAdapter extends ArrayAdapter<Course>{
//private Context mContext;
//ArrayList<Course> mylist=new ArrayList<>();
public CourseAdapter(Context context, int resource, List<Course> objects) {//resourse =list_item
super(context,resource,objects);
}
//#Override public int getCount() {return mylist.size();}
//#Override public Object getItem(int position) {return mylist.get(position).toString();}
/*#Override
public long getItemId(int position) {
return position;
}
public void onItemSelected(int position) {}
public class ViewHolder {
public TextView coursetext;
public CheckBox tick;}*/
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
convertView = ((Activity) getContext()).getLayoutInflater().inflate(R.layout.list_item, parent, false);
}
TextView courseTextView = (TextView) convertView.findViewById(R.id.listItemTextView);
Course course=getItem(position);
courseTextView.setText(course.getCourseName());
/* TODO Auto-generated method stub
ViewHolder view = null;
LayoutInflater inflator = ((Activity) mContext).getLayoutInflater();
if (view == null) {
view = new ViewHolder();
convertView = inflator.inflate( R.layout.list_item, null);
view.coursetext= (TextView) convertView.findViewById(R.id.listItemTextView);
view.tick=(CheckBox)convertView.findViewById(R.id.checkButton);
view.tick.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener(){
#Override
public void onCheckedChanged(CompoundButton button, boolean isChecked) {
int getPosition = (Integer) button.getTag(); // Here
// we get the position that we have set for the checkbox using setTag.
mylist.get(getPosition).setChecked(button.isChecked()); // Set the value of checkbox to maintain its state.
if (isChecked) {
//do sometheing here
}
else
{
// code here
}
}
});
convertView.setTag(view);
} else {
view = (ViewHolder) convertView.getTag();
}
view.tick.setTag(position);
view.coursetext.setText("" + mylist.get(position).getCourseName());
view.tick.setChecked(mylist.get(position).isChecked());*/
return convertView;
}
}
any help ??
edit: this is what the log shows
02-14 15:22:26.838 15829-15829/? I/art: Late-enabling -Xcheck:jni
02-14 15:22:26.932 15829-15829/com.example.android.mycoursesapp W/System: ClassLoader referenced unknown path: /data/app/com.example.android.mycoursesapp-2/lib/arm64
02-14 15:22:26.938 15829-15829/com.example.android.mycoursesapp I/InstantRun: Instant Run Runtime started. Android package is com.example.android.mycoursesapp, real application class is null.
02-14 15:22:27.460 15829-15829/com.example.android.mycoursesapp W/System: ClassLoader referenced unknown path: /data/app/com.example.android.mycoursesapp-2/lib/arm64
02-14 15:22:27.585 15829-15829/com.example.android.mycoursesapp I/FA: App measurement is starting up, version: 10084
02-14 15:22:27.586 15829-15829/com.example.android.mycoursesapp I/FA: To enable debug logging run: adb shell setprop log.tag.FA VERBOSE
02-14 15:22:27.604 15829-15829/com.example.android.mycoursesapp I/FA: To enable faster debug mode event logging run:
adb shell setprop debug.firebase.analytics.app com.example.android.mycoursesapp
02-14 15:22:27.684 15829-15829/com.example.android.mycoursesapp I/HwCust: Constructor found for class android.app.HwCustAlarmManagerImpl
02-14 15:22:27.694 15829-15829/com.example.android.mycoursesapp I/FirebaseInitProvider: FirebaseApp initialization successful
02-14 15:22:27.887 15829-15829/com.example.android.mycoursesapp W/art: Before Android 4.1, method android.graphics.PorterDuffColorFilter android.support.graphics.drawable.VectorDrawableCompat.updateTintFilter(android.graphics.PorterDuffColorFilter, android.content.res.ColorStateList, android.graphics.PorterDuff$Mode) would have incorrectly overridden the package-private method in android.graphics.drawable.Drawable
02-14 15:22:28.183 15829-15829/com.example.android.mycoursesapp I/DynamiteModule: Considering local module com.google.android.gms.firebase_database:4 and remote module com.google.android.gms.firebase_database:5
02-14 15:22:28.183 15829-15829/com.example.android.mycoursesapp I/DynamiteModule: Selected remote version of com.google.android.gms.firebase_database, version >= 5
02-14 15:22:28.204 15829-15829/com.example.android.mycoursesapp W/System: ClassLoader referenced unknown path: /data/user/0/com.google.android.gms/app_chimera/m/00000007/n/arm64-v8a
02-14 15:22:28.273 15829-15829/com.example.android.mycoursesapp I/HwSecImmHelper: mSecurityInputMethodService is null
02-14 15:22:28.286 15829-15829/com.example.android.mycoursesapp E/HAL: load: id=gralloc != hmi->id=gralloc
02-14 15:22:28.301 15829-15906/com.example.android.mycoursesapp I/System: core_booster, getBoosterConfig = false
02-14 15:22:28.333 15829-15905/com.example.android.mycoursesapp E/HAL: load: id=gralloc != hmi->id=gralloc
02-14 15:22:28.333 15829-15905/com.example.android.mycoursesapp I/OpenGLRenderer: Initialized EGL, version 1.4
02-14 15:22:28.338 15829-15905/com.example.android.mycoursesapp W/OpenGLRenderer: load: so=/system/lib64/libhwuibp.so
dlopen failed: library "/system/lib64/libhwuibp.so" not found
02-14 15:22:28.338 15829-15905/com.example.android.mycoursesapp W/OpenGLRenderer: Initialize Binary Program Cache: Load Failed
02-14 15:22:28.338 15829-15905/com.example.android.mycoursesapp E/HAL: load: id=gralloc != hmi->id=gralloc
02-14 15:22:29.325 15829-15939/com.example.android.mycoursesapp I/System: core_booster, getBoosterConfig = false
02-14 15:22:30.704 15829-15829/com.example.android.mycoursesapp I/Process: Sending signal. PID: 15829 SIG: 9

move below two lines to after setContentView(R.layout.activity_main); line.
mCourseListView = (ListView) findViewById(R.id.courseListView);
mCheckBox=(CheckBox) findViewById(checkButton);

Related

Unable to start activity ComponentInfo NPE [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 3 years ago.
I am trying to make an app on Android, using Kotlin and Java.
My inspiration comes from this tutorial:
https://www.youtube.com/watch?v=Qg3L_B9--zY
I changed it a little bit, and now I have a beautiful error:
"Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.pm.ApplicationInfo android.content.Context.getApplicationInfo()' on a null object reference"
Here is the error log:
11-21 10:46:03.006 27125-27125/? E/libprocessgroup: failed to make and chown /acct/uid_10058: Read-
only file system
11-21 10:46:03.006 27125-27125/? W/Zygote: createProcessGroup failed, kernel missing CONFIG_CGROUP_CPUACCT?
11-21 10:46:03.006 27125-27125/? I/art: Not late-enabling -Xcheck:jni (already on)
11-21 10:46:03.079 27125-27125/com.example.budgetapp I/System.out: Util Constructor
11-21 10:46:03.143 27125-27125/com.example.budgetapp E/MainActivity: before onCreate()
11-21 10:46:03.150 27125-27125/com.example.budgetapp W/art: Before Android 4.1, method android.graphics.PorterDuffColorFilter androidx.vectordrawable.graphics.drawable.VectorDrawableCompat.updateTintFilter(android.graphics.PorterDuffColorFilter, android.content.res.ColorStateList, android.graphics.PorterDuff$Mode) would have incorrectly overridden the package-private method in android.graphics.drawable.Drawable
11-21 10:46:03.183 27125-27125/com.example.budgetapp E/MainActivity: after onCreate()
11-21 10:46:03.206 27125-27125/com.example.budgetapp I/art: Rejecting re-init on previously-failed class java.lang.Class<androidx.core.view.ViewCompat$2>
11-21 10:46:03.206 27125-27125/com.example.budgetapp I/art: Rejecting re-init on previously-failed class java.lang.Class<androidx.core.view.ViewCompat$2>
11-21 10:46:03.275 27125-27125/com.example.budgetapp E/MainActivity: after setContentView()
11-21 10:46:03.275 27125-27125/com.example.budgetapp D/AndroidRuntime: Shutting down VM
--------- beginning of crash
11-21 10:46:03.276 27125-27125/com.example.budgetapp E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.budgetapp, PID: 27125
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.budgetapp/com.example.budgetapp.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.pm.ApplicationInfo android.content.Context.getApplicationInfo()' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2325)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2387)
at android.app.ActivityThread.access$800(ActivityThread.java:151)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1303)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5254)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.pm.ApplicationInfo android.content.Context.getApplicationInfo()' on a null object reference
at android.content.ContextWrapper.getApplicationInfo(ContextWrapper.java:149)
at android.view.ContextThemeWrapper.getTheme(ContextThemeWrapper.java:99)
at android.content.Context.obtainStyledAttributes(Context.java:437)
at androidx.appcompat.app.AppCompatDelegateImpl.createSubDecor(AppCompatDelegateImpl.java:692)
at androidx.appcompat.app.AppCompatDelegateImpl.ensureSubDecor(AppCompatDelegateImpl.java:659)
at androidx.appcompat.app.AppCompatDelegateImpl.findViewById(AppCompatDelegateImpl.java:479)
at androidx.appcompat.app.AppCompatActivity.findViewById(AppCompatActivity.java:214)
at Util.setupUIViews(Util.java:43)
at com.example.budgetapp.MainActivity.onCreate(MainActivity.kt:27)
at android.app.Activity.performCreate(Activity.java:5990)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1106)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2278)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2387) 
at android.app.ActivityThread.access$800(ActivityThread.java:151) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1303) 
at android.os.Handler.dispatchMessage(Handler.java:102) 
at android.os.Looper.loop(Looper.java:135) 
at android.app.ActivityThread.main(ActivityThread.java:5254) 
at java.lang.reflect.Method.invoke(Native Method) 
at java.lang.reflect.Method.invoke(Method.java:372) 
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698) 
And here are my classes:
MainActivity.kt:
package com.example.budgetapp
import Util
import android.app.DatePickerDialog
import android.os.Bundle
import android.util.Log
import androidx.appcompat.app.AppCompatActivity
import kotlinx.android.synthetic.main.activity_main.*
import java.util.*
class MainActivity : AppCompatActivity() {
private val tag = "MainActivity"
var util = Util()
override fun onCreate(savedInstanceState: Bundle?) {
Log.e(tag, "before onCreate()")
super.onCreate(savedInstanceState)
Log.e(tag, "after onCreate()")
setContentView(R.layout.activity_main)
Log.e(tag, "after setContentView()")
util.setupUIViews()
Log.e(tag, "after setupUIView()")
util.initToolbar()
Log.e(tag, "after initToolbar()")
util.setupListView()
Log.e(tag, "after setupListView()")
//Calendars:
val c = Calendar.getInstance()
val year = c.get(Calendar.YEAR)
val month = c.get(Calendar.MONTH)
val day = c.get(Calendar.DAY_OF_MONTH)
val c2 = Calendar.getInstance()
val year2 = c2.get(Calendar.YEAR)
val month2 = c2.get(Calendar.MONTH)
val day2 = c2.get(Calendar.DAY_OF_MONTH)
Log.e(tag, "year1: $year")
Log.e(tag, "month1: $month")
Log.e(tag, "month2: $month2")
Log.e(tag, "day1: $day")
//button click to show DatePickerDialog
pickDateBtn.setOnClickListener {
val dpd = DatePickerDialog(
this,
DatePickerDialog.OnDateSetListener {_, mYear, mMonth, mDay ->
var monthSel=mMonth+1
dateTv2.text = "$mDay/$monthSel/$mYear"
},
year,
month,
day
)
dpd.show()
val dpd2 = DatePickerDialog(
this,
DatePickerDialog.OnDateSetListener {_, mYear2, mMonth2, mDay2 ->
var monthSel2=mMonth2+1
dateTv.text = "$mDay2/$monthSel2/$mYear2"
},
year2,
month2,
day2
)
dpd2.show()
}
}
}
SimpleAdapter.java:
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import com.example.budgetapp.R;
public class SimpleAdapter extends BaseAdapter {
public Context mContext;
private LayoutInflater layoutInflater;
private TextView title, description;
private String[] titleArray, descriptionArray;
private ImageView imageView;
public SimpleAdapter(Context context, String[] title, String [] description){
mContext= context;
titleArray=title;
descriptionArray= description;
layoutInflater= LayoutInflater.from(context);
}
#Override
public int getCount(){
return titleArray.length;
}
#Override
public Object getItem(int position) {
return titleArray[position];
}
#Override
public long getItemId(int position){
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if(convertView == null) {
layoutInflater.inflate(R.layout.main_activity_single_item, null);
}
title= convertView.findViewById(R.id.tvMain);
description = convertView.findViewById(R.id.tvDescription);
imageView = convertView.findViewById(R.id.ivMain);
title.setText(titleArray[position]);
description.setText(descriptionArray[position]);
if(titleArray[position].equalsIgnoreCase("Timetable")){
imageView.setImageResource(R.drawable.timetable);
}else if(titleArray[position].equalsIgnoreCase("Subjects")){
imageView.setImageResource(R.drawable.book);
}else if(titleArray[position].equalsIgnoreCase("Faculty")) {
imageView.setImageResource(R.drawable.play);
}else{
imageView.setImageResource(R.drawable.settings);
}
return convertView;
}
}
and Util.java:
import android.widget.ListView;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import com.example.budgetapp.R;
import java.util.logging.Logger;
public class Util extends AppCompatActivity {
public Util(){
System.out.println("Util Constructor");
}
public Toolbar getToolbar() {
return toolbar;
}
public void setToolbar(Toolbar toolbar) {
this.toolbar = toolbar;
}
public ListView getListView() {
return listView;
}
public void setListView(ListView listView) {
this.listView = listView;
}
#Override
public String toString() {
return "Util{" +
"toolbar=" + toolbar +
", listView=" + listView +
'}';
}
private Toolbar toolbar;
private ListView listView;
Logger logger;
public void setupUIViews(){
toolbar = findViewById(R.id.ToolbarMain);
logger.info("inside Util class, setupUiViews, before findViewById(lvMain)");
listView = findViewById(R.id.lvMain);
}
public void initToolbar(){
setSupportActionBar(toolbar);
getSupportActionBar().setTitle(" App");
}
public void setupListView(){
String[] title = getResources().getStringArray(R.array.Main);
String[] description=getResources().getStringArray(R.array.Description);
SimpleAdapter simpleAdapter = new SimpleAdapter(this, title, description);
listView.setAdapter(simpleAdapter);
}
}
The code crushes before entering into setupUIViews() method from Util class.
Can you please, please take a look and tell me how can I resolve the issue ?
I debugged, but did not understand where the problem comes from.
Also, looked to other similar questions, but each exemple is specific, so I cannot extrapolate to my situation.
Thank you very much for your time and help!
you call util. setupUIViews(), in the inner method,it called findViewById(R.id.ToolbarMain). this method is belonged to Activity, we look at the source code
return getWindow().findViewById(id);
//in the window, (PhoneWindow)
#Nullable
public <T extends View> T findViewById(#IdRes int id) {
return getDecorView().findViewById(id);
}
// the DecorView is the basic view, it set when you call setContentView
public void setContentView(#LayoutRes int layoutResID) {
getWindow().setContentView(layoutResID);
initWindowDecorActionBar();
}
//PhoneWindow setContentView
#Override
public void setContentView(View view) {
setContentView(view, new ViewGroup.LayoutParams(MATCH_PARENT, MATCH_PARENT));
}
#Override
public void setContentView(View view, ViewGroup.LayoutParams params) {
// decor, when theme attributes and the like are crystalized. Do not
// check the feature
// before this happens.
if (mContentParent == null) {
installDecor(); // this method init DecorView
} else if (!hasFeature(FEATURE_CONTENT_TRANSITIONS)) {
mContentParent.removeAllViews();
}
...
}
but you do not call util setContenView to set its view. so it reports the error.
and your code writes way is wrong. we set view in activity or fragment own class;
we cannot use another activity to set other activities.
In android, every activity has its own window. try to move the Utils method into MainActiviy.
The util class is extending from AppCompatActivity but is not properly initialized. You can't use AppCompatActivity in that way. Instead you need to do something like:
class MainActivity : AppCompatActivity() {
private val tag = "MainActivity"
lateinit var util: Util
override fun onCreate(savedInstanceState: Bundle?) {
util = Util(this)
}
}
And the Util (in kotlin) class:
class Util(private delegate:MainActivity) {
public void setupUIViews(){
toolbar = delegate.findViewById(R.id.ToolbarMain);
listView = delegate.findViewById(R.id.lvMain);
}
}
Also, I think that using this pattern and move all view-related stuff to a "Util" class is not the best. You will have better results using other patterns like MVP or MVVM.

No image showing on recyclerview with parse server

I'm very new to Android programming but with a little bit knowledge in java programming and I have an issue with connecting my Parse database to my RecyclerView. Nothing appears on the screen when the activity is launch. I have Log all the output query from Parse server and manage to get every rows of "image_url" but it seems to have problem when i try to output the image. I don't understand where the problem comes in and I really need explanation with this.
MainActivity
package sg.com.test.parseandroid;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.widget.Toast;
import com.parse.FindCallback;
import com.parse.ParseException;
import com.parse.ParseObject;
import com.parse.ParseQuery;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends AppCompatActivity {
private RecyclerView recyclerView;
private GridLayoutManager gridLayoutManager;
private static CustomAdapter adapter;
private List<MyData> data_list;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
recyclerView = (RecyclerView) findViewById(R.id.recycler_view);
data_list = new ArrayList<>();
gridLayoutManager = new GridLayoutManager(this, 2);
recyclerView.setLayoutManager(gridLayoutManager);
ParseQuery<ParseObject> query = ParseQuery.getQuery("Post");
query.findInBackground(new FindCallback<ParseObject>() {
public void done(List<ParseObject> postList, ParseException e) {
if (e == null) {
for (ParseObject obj : postList) {
MyData data = new MyData(obj.getObjectId(), obj.getString("image_url"));
data_list.add(data);
Log.d("MAINACTIVITY", String.format("objectid- %s", data_list.get(postList.indexOf(obj)).getObjectId()));
}
} else {
Toast.makeText(MainActivity.this, "Something went wrong...", Toast.LENGTH_SHORT).show();
}
}
});
adapter = new CustomAdapter(this, data_list);
recyclerView.setAdapter(adapter);
}
}
CustomAdapter.java
package sg.com.test.parseandroid;
import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import com.bumptech.glide.Glide;
import java.util.List;
public class CustomAdapter extends RecyclerView.Adapter<CustomAdapter.ViewHolder> {
private Context context;
private List<MyData> my_data;
public CustomAdapter(Context context, List<MyData> my_data) {
this.context = context;
this.my_data = my_data;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.card_view, parent, false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(ViewHolder holder, int position) {
Glide.with(context).load(my_data.get(position).getImage_url()).into(holder.imageView);
}
#Override
public int getItemCount() {
return my_data.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
private ImageView imageView;
public ViewHolder(View itemView) {
super(itemView);
imageView = (ImageView) itemView.findViewById((R.id.image));
}
}
}
MyData.java
package sg.com.test.parseandroid;
public class MyData {
private String objectId, image_url;
MyData(String objectId, String image_url) {
this.objectId = objectId;
this.image_url = image_url;
}
public String getObjectId() {
return objectId;
}
public void setObjectId(String objectId) {
this.objectId = objectId;
}
public String getImage_url() {
return image_url;
}
public void setImage_url(String image_url) {
this.image_url = image_url;
}
}
Logcat
02-14 19:22:29.157 1728-1728/? I/zygote: Not late-enabling -Xcheck:jni (already on)
02-14 19:22:29.208 1728-1728/? W/zygote: Unexpected CPU variant for X86 using defaults: x86
02-14 19:22:29.523 1728-1728/sg.com.test.parseandroid I/InstantRun: starting instant run server: is main process
02-14 19:22:29.622 1728-1766/sg.com.test.parseandroid D/NetworkSecurityConfig: No Network Security Config specified, using platform default
02-14 19:22:29.933 1728-1773/sg.com.test.parseandroid D/OpenGLRenderer: HWUI GL Pipeline
02-14 19:22:29.984 1728-1773/sg.com.test.parseandroid I/zygote: android::hardware::configstore::V1_0::ISurfaceFlingerConfigs::hasWideColorDisplay retrieved: 0
02-14 19:22:29.985 1728-1773/sg.com.test.parseandroid I/OpenGLRenderer: Initialized EGL, version 1.4
02-14 19:22:29.985 1728-1773/sg.com.test.parseandroid D/OpenGLRenderer: Swap behavior 1
02-14 19:22:29.985 1728-1773/sg.com.test.parseandroid W/OpenGLRenderer: Failed to choose config with EGL_SWAP_BEHAVIOR_PRESERVED, retrying without...
02-14 19:22:29.985 1728-1773/sg.com.test.parseandroid D/OpenGLRenderer: Swap behavior 0
02-14 19:22:30.001 1728-1773/sg.com.test.parseandroid D/EGL_emulation: eglCreateContext: 0x9ec85420: maj 2 min 0 rcv 2
02-14 19:22:30.021 1728-1773/sg.com.test.parseandroid D/EGL_emulation: eglMakeCurrent: 0x9ec85420: ver 2 0 (tinfo 0x9ec83310)
02-14 19:22:30.078 1728-1773/sg.com.test.parseandroid D/EGL_emulation: eglMakeCurrent: 0x9ec85420: ver 2 0 (tinfo 0x9ec83310)
02-14 19:22:31.231 1728-1728/sg.com.test.parseandroid D/MAINACTIVITY: objectId- caNtpHNOZB
02-14 19:22:31.231 1728-1728/sg.com.test.parseandroid D/MAINACTIVITY: objectId- G5eDwzYS8p
02-14 19:22:31.231 1728-1728/sg.com.test.parseandroid D/MAINACTIVITY: objectId- aap5bR7Xb5
Updates:
Can't get any LOG in CustomAdapter.java
card_view.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent"
android:layout_height="match_parent">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<ImageView
android:id="#+id/image"
android:layout_width="match_parent"
android:layout_height="200dp"
android:scaleType="centerCrop"/>
</RelativeLayout>
</android.support.constraint.ConstraintLayout>
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.RecyclerView
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="sg.com.test.parseandroid.MainActivity"
android:id="#+id/recycler_view"/>
I will get an error if i Log the data_list
ParseQuery<ParseObject> query = ParseQuery.getQuery("Post");
query.findInBackground(new FindCallback<ParseObject>() {
public void done(List<ParseObject> postList, ParseException e) {
if (e == null) {
for (ParseObject obj : postList) {
MyData data = new MyData(obj.getObjectId(), obj.getString("image_url"));
data_list.add(data);
Log.d("MAINACTIVITY", String.format("objectid- %s", data_list.get(postList.indexOf(obj)).getImage_url()));
}
} else {
Toast.makeText(MainActivity.this, "Something went wrong...", Toast.LENGTH_SHORT).show();
}
}
});
MyData data = data_list.get(0);
Log.d("MainActivity.onCreate", data.getObjectId());
adapter = new CustomAdapter(this, data_list);
adapter.notifyDataSetChanged();
recyclerView.setAdapter(adapter);
Logcat
02-15 05:26:43.820 16722-16722/? E/AndroidRuntime: FATAL EXCEPTION: main
Process: sg.com.creertech.parseandroid, PID: 16722
java.lang.RuntimeException: Unable to start activity ComponentInfo{sg.com.creertech.parseandroid/sg.com.creertech.parseandroid.MainActivity}: java.lang.IndexOutOfBoundsException: Index: 0, Size: 0
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2778)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2856)
at android.app.ActivityThread.-wrap11(Unknown Source:0)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1589)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:164)
at android.app.ActivityThread.main(ActivityThread.java:6494)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:438)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:807)
Caused by: java.lang.IndexOutOfBoundsException: Index: 0, Size: 0
at java.util.ArrayList.get(ArrayList.java:437)
at sg.com.creertech.parseandroid.MainActivity.onCreate(MainActivity.java:52)
at android.app.Activity.performCreate(Activity.java:6999)
at android.app.Activity.performCreate(Activity.java:6990)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1214)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2731)
At first, insert log inside every fuctions in CustomAdapter and see if the data is reaching here or not. eg.
Log.d("CustomAdapter", "size of data==> "+my_data.size());
If all good then try this code inside onCreateViewHolder(). Instead of parent, false try null. This may help
View view = LayoutInflater.from(context.inflate(R.layout.card, null);
Also can you show the card.xml layout??

Android Java Adapter, PHP JSON

Can someone give me a example of a right json file and php, so I can use it in the Android GET method? I think my files are wrong. This are the newest files regarding JSON and PHP
data.json
{
"Heroes":
[
{
"name":"Superman",
"about":"testdesc",
"image":"google.de/image.png"
},
{
"name":"Superman",
"about":"testdesc",
"image":"google.de/image.png"
},
{
"name":"Superman",
"about":"testdesc",
"image":"google.de/image.png"
},
{
"name":"Superman",
"about":"testdesc",
"image":"google.de/image.png"
}
]
}
data.php
<?php
$jsonData = file_get_contents("data.json");
$json = json_encode($jsonData,true);
header('Content-Type: application/json');
echo $json;
?>
I am new to Android App's coding.
May you can help me out, with a stupid problem.
I've tried to make an app from a youtube tutorial,
there it workes fine but I got several problems now I really need to fix.
The app is basicly an App that shows me a RecyclerViewCard with an Image, HeaderText and About text, the content is in a php file on my localhost.
<?php
$json2 = array(
"error" => "false",
"Heroes" => array(
'name' => 'Spiderman',
'about' => 'Spiderman ist ein Spinnenheld mit einem leckeren Schwanz',
'image' => 'www.google.de/info.png'
)
);
?>
So this is basicly the Json code to get it in my app, I hope this is right. If not please help me out with the right json code.
The error I get is following:
06-29 18:03:47.292 5249-5249/? I/art: Not late-enabling -Xcheck:jni (already on)
06-29 18:03:47.293 5249-5249/? W/art: Unexpected CPU variant for X86 using defaults: x86
06-29 18:03:47.714 5249-5249/de.example.kevin.superheroes W/System: ClassLoader referenced unknown path: /data/app/de.example.kevin.superheroes-2/lib/x86
06-29 18:03:47.764 5249-5249/de.example.kevin.superheroes I/InstantRun: starting instant run server: is main process
06-29 18:03:47.954 5249-5249/de.example.kevin.superheroes W/art: Before Android 4.1, method android.graphics.PorterDuffColorFilter android.support.graphics.drawable.VectorDrawableCompat.updateTintFilter(android.graphics.PorterDuffColorFilter, android.content.res.ColorStateList, android.graphics.PorterDuff$Mode) would have incorrectly overridden the package-private method in android.graphics.drawable.Drawable
06-29 18:03:48.574 5249-5287/de.example.kevin.superheroes D/NetworkSecurityConfig: No Network Security Config specified, using platform default
06-29 18:03:48.639 5249-5285/de.example.kevin.superheroes I/OpenGLRenderer: Initialized EGL, version 1.4
06-29 18:03:48.639 5249-5285/de.example.kevin.superheroes D/OpenGLRenderer: Swap behavior 1
06-29 18:03:48.647 5249-5285/de.example.kevin.superheroes W/OpenGLRenderer: Failed to choose config with EGL_SWAP_BEHAVIOR_PRESERVED, retrying without...
06-29 18:03:48.647 5249-5285/de.example.kevin.superheroes D/OpenGLRenderer: Swap behavior 0
06-29 18:03:48.949 5249-5249/de.example.kevin.superheroes E/RecyclerView: No adapter attached; skipping layout
06-29 18:03:49.168 5249-5249/de.example.kevin.superheroes W/System.err: org.json.JSONException: End of input at character 0 of
06-29 18:03:49.168 5249-5249/de.example.kevin.superheroes W/System.err: at org.json.JSONTokener.syntaxError(JSONTokener.java:449)
06-29 18:03:49.168 5249-5249/de.example.kevin.superheroes W/System.err: at org.json.JSONTokener.nextValue(JSONTokener.java:97)
06-29 18:03:49.168 5249-5249/de.example.kevin.superheroes W/System.err: at org.json.JSONObject.<init>(JSONObject.java:156)
06-29 18:03:49.168 5249-5249/de.example.kevin.superheroes W/System.err: at org.json.JSONObject.<init>(JSONObject.java:173)
06-29 18:03:49.168 5249-5249/de.example.kevin.superheroes W/System.err: at de.example.kevin.superheroes.MainActivity$1.onResponse(MainActivity.java:60)
06-29 18:03:49.168 5249-5249/de.example.kevin.superheroes W/System.err: at de.example.kevin.superheroes.MainActivity$1.onResponse(MainActivity.java:55)
06-29 18:03:49.168 5249-5249/de.example.kevin.superheroes W/System.err: at com.android.volley.toolbox.StringRequest.deliverResponse(StringRequest.java:60)
06-29 18:03:49.168 5249-5249/de.example.kevin.superheroes W/System.err: at com.android.volley.toolbox.StringRequest.deliverResponse(StringRequest.java:30)
06-29 18:03:49.168 5249-5249/de.example.kevin.superheroes W/System.err: at com.android.volley.ExecutorDelivery$ResponseDeliveryRunnable.run(ExecutorDelivery.java:99)
06-29 18:03:49.169 5249-5249/de.example.kevin.superheroes W/System.err: at android.os.Handler.handleCallback(Handler.java:751)
06-29 18:03:49.169 5249-5249/de.example.kevin.superheroes W/System.err: at android.os.Handler.dispatchMessage(Handler.java:95)
06-29 18:03:49.169 5249-5249/de.example.kevin.superheroes W/System.err: at android.os.Looper.loop(Looper.java:154)
06-29 18:03:49.169 5249-5249/de.example.kevin.superheroes W/System.err: at android.app.ActivityThread.main(ActivityThread.java:6119)
06-29 18:03:49.169 5249-5249/de.example.kevin.superheroes W/System.err: at java.lang.reflect.Method.invoke(Native Method)
06-29 18:03:49.169 5249-5249/de.example.kevin.superheroes W/System.err: at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886)
06-29 18:03:49.169 5249-5249/de.example.kevin.superheroes W/System.err: at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776)
06-29 18:03:49.240 5249-5249/de.example.kevin.superheroes W/art: Before Android 4.1, method int android.support.v7.widget.ListViewCompat.lookForSelectablePosition(int, boolean) would have incorrectly overridden the package-private method in android.widget.ListView
The MainActivity:
package de.example.kevin.superheroes;
import android.app.LauncherActivity;
import android.app.ProgressDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.widget.ImageView;
import android.widget.Toast;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.VolleyLog;
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;
public class MainActivity extends AppCompatActivity {
private RecyclerView recyclerView = null;
private RecyclerView.Adapter adapter = null;
private List<ListItem> listItems = null;
private static final String URL_DATA = "http://192.168.178.29/android/data.php";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_layout);
recyclerView = (RecyclerView) findViewById(R.id.recyclerView);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
listItems = new ArrayList<>();
loadRecyclerViewData();
}
private void loadRecyclerViewData(){
final ProgressDialog progressDialog = new ProgressDialog(this);
progressDialog.setMessage("Content is loading ...");
progressDialog.show();
StringRequest stringRequest = new StringRequest(Request.Method.GET, URL_DATA, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
progressDialog.dismiss();
try {
JSONObject jsonObject = new JSONObject(response);
JSONArray array = jsonObject.getJSONArray("Heroes");
for(int i = 0; i<array.length(); i++){
JSONObject o = array.getJSONObject(i);
ListItem item = new ListItem(
o.getString("name"),
o.getString("about"),
o.getString("image")
);
listItems.add(item);
}
adapter = new MyAdapter(listItems,getApplicationContext());
recyclerView.setAdapter(adapter);
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
progressDialog.dismiss();
Toast.makeText(getApplicationContext(), error.getMessage(), Toast.LENGTH_SHORT).show();
}
});
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
}
}
ListItem.java
package de.example.kevin.superheroes;
import android.widget.ImageView;
public class ListItem {
public ListItem(String img_url, String head, String desc) {
this.img_url = img_url;
this.head = head;
this.desc = desc;
}
private String img_url = null;
private String head = null;
private String desc = null;
public String getImg_url() {
return img_url;
}
public String getHead() {
return head;
}
public String getDesc() {
return desc;
}
}
MyAdapter
package de.example.kevin.superheroes;
import android.content.Context;
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.List;
public class MyAdapter extends RecyclerView.Adapter<MyAdapter.ViewHolder> {
private List<ListItem> listItems = null;
private Context context = null;
public MyAdapter(List<ListItem> listItems, Context context) {
this.listItems = listItems;
this.context = context;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext())
.inflate(R.layout.list_item,parent,false);
return new ViewHolder(v);
}
#Override
public void onBindViewHolder(ViewHolder holder, int position) {
ListItem listItem = listItems.get(position);
holder.textViewHead.setText(listItem.getHead());
holder.textViewDesc.setText(listItem.getDesc());
}
#Override
public int getItemCount() {
return listItems.size();
}
public class ViewHolder extends RecyclerView.ViewHolder{
public TextView textViewHead = null;
public TextView textViewDesc = null;
public ViewHolder(View itemView) {
super(itemView);
textViewHead = (TextView) itemView.findViewById(R.id.textViewHead);
textViewDesc = (TextView) itemView.findViewById(R.id.textViewDesc);
}
}
}
I would be so glad if you can help me !
If you have any question please ask.
Thanks
After editing my json code I get following error:
PHP
<?php
$json2 = array(
"error" => "false",
"Heroes" => array(
'name' => 'Spiderman',
'about' => 'Spiderman ist ein Spinnenheld mit einem ',
'image' => 'www.google.de/info.png'
)
);
echo json_encode($json2);
?>
No I get this huge errors :
I have postet it on pastebin because its to big for here:
https://pastebin.com/RAuNfZGm
Since it says, "org.json.JSONException: End of input at character 0". It essentially means that you are not returning anything from your php. Like Vaibhav said, you need to encode your array in json using json_encode() and echo the result.
Further Answer
You would need,
<?php
class Hero {
// Creating some properties
public $name;
public $about;
public $image;
// Assigning the values
public function __construct($name, $about, $image) {
$this->name = $name;
$this->about = $about;
$this->image = $image;
}
}
$array_heros[0] = new Hero('Spiderman', 'Spiderman-about', 'image_link');
$array_heros[1] = new Hero('Batman', 'Batman-about', 'image_link');
$json2 = array(
"error" => "false",
"Heroes" => $array_heros
);
echo json_encode($json2);
?>
In you php file its just creating array not json
to create json and return it use last line.
`
<?php
$json2 = array(
"error" => "false",
"Heroes" => array(
'name' => 'Spiderman',
'about' => 'Spiderman ist ein Spinnenheld mit einem leckeren Schwanz',
'image' => 'www.google.de/info.png'
)
);
echo json_encode($json2);
?>`

Implementing RecyclerView to show the contacts of the device, using ContactsContract but there is error. I've involved the gradle error code below

I have tried to show the device contacts in the recyclerview. I'm using ContactsContract to populate the list. I think the error is that the contacts are not being fetched but I don't know why.
Can you please check my mistake?
Error:
10-11 17:50:21.550 27076-27076/com.example.anubh.contactsearch D/Proxy: setHttpRequestCheckHandler
10-11 17:50:21.694 27076-27076/com.example.anubh.contactsearch D/OpenSSLLib: OpensslErr:Module:13(114:155); file:external/openssl/crypto/asn1/asn1_lib.c ;Line:142;Function:ASN1_get_object
10-11 17:50:22.532 27076-27076/com.example.anubh.contactsearch D/ActivityThread: BIND_APPLICATION handled : 0 / AppBindData{appInfo=ApplicationInfo{14eaff4b com.example.anubh.contactsearch}}
10-11 17:50:22.533 27076-27076/com.example.anubh.contactsearch V/ActivityThread: Handling launch of ActivityRecord{d9bd28 token=android.os.BinderProxy#2947ea41 {com.example.anubh.contactsearch/com.example.anubh.contactsearch.MainActivity}}
10-11 17:50:22.803 27076-27076/com.example.anubh.contactsearch V/ActivityThread: ActivityRecord{d9bd28 token=android.os.BinderProxy#2947ea41 {com.example.anubh.contactsearch/com.example.anubh.contactsearch.MainActivity}}: app=android.app.Application#4684527, appName=com.example.anubh.contactsearch, pkg=com.example.anubh.contactsearch, comp={com.example.anubh.contactsearch/com.example.anubh.contactsearch.MainActivity}, dir=/data/app/com.example.anubh.contactsearch-1/base.apk
10-11 17:50:22.941 27076-27076/com.example.anubh.contactsearch W/art: Before Android 4.1, method android.graphics.PorterDuffColorFilter android.support.graphics.drawable.VectorDrawableCompat.updateTintFilter(android.graphics.PorterDuffColorFilter, android.content.res.ColorStateList, android.graphics.PorterDuff$Mode) would have incorrectly overridden the package-private method in android.graphics.drawable.Drawable
10-11 17:50:23.147 27076-27076/com.example.anubh.contactsearch I/AppCompatViewInflater: app:theme is now deprecated. Please move to using android:theme instead.
10-11 17:50:23.440 27076-27076/com.example.anubh.contactsearch D/ActivityThread: hoder:android.app.IActivityManager$ContentProviderHolder#36d02546,provider,holder.Provider:android.content.ContentProviderProxy#1c1f6307
10-11 17:50:23.482 27076-27076/com.example.anubh.contactsearch I/System.out: Name: Micromax carephone: 18605008286
10-11 17:50:23.486 27076-27076/com.example.anubh.contactsearch D/AndroidRuntime: Shutting down VM
10-11 17:50:23.487 27076-27076/com.example.anubh.contactsearch E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.anubh.contactsearch, PID: 27076
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.anubh.contactsearch/com.example.anubh.contactsearch.MainActivity}: java.lang.NullPointerException: Attempt to invoke interface method 'boolean java.util.List.add(java.lang.Object)' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2455)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2517)
at android.app.ActivityThread.access$800(ActivityThread.java:162)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1412)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:189)
at android.app.ActivityThread.main(ActivityThread.java:5530)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:950)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:745)
Caused by: java.lang.NullPointerException: Attempt to invoke interface method 'boolean java.util.List.add(java.lang.Object)' on a null object reference
at com.example.anubh.contactsearch.myAdapter.<init>(myAdapter.java:71)
at com.example.anubh.contactsearch.MainActivity.onCreate(MainActivity.java:30)
at android.app.Activity.performCreate(Activity.java:5966)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1106)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2408)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2517) 
at android.app.ActivityThread.access$800(ActivityThread.java:162) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1412) 
at android.os.Handler.dispatchMessage(Handler.java:106) 
at android.os.Looper.loop(Looper.java:189) 
at android.app.ActivityThread.main(ActivityThread.java:5530) 
at java.lang.reflect.Method.invoke(Native Method) 
at java.lang.reflect.Method.invoke(Method.java:372) 
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:950) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:745) 
10-11 17:50:29.394 27076-27089/com.example.anubh.contactsearch W/CursorWrapperInner: Cursor finalized without prior close()
MainActivity.java
package com.example.anubh.contactsearch;
import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity {
Toolbar toolbar;
RecyclerView recyclerView;
myAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
//getSupportActionBar().setTitle("Contacts");
getSupportActionBar().setSubtitle("Search");
getSupportActionBar().setIcon(R.drawable.ic_action_toolbar);
recyclerView = (RecyclerView) findViewById(R.id.recyclerview);
adapter = new myAdapter(this);
recyclerView.setAdapter(adapter);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu,menu);
return super.onCreateOptionsMenu(menu);
}
}
myAdapter.java
package com.example.anubh.contactsearch;
import android.content.ContentResolver;
import android.content.Context;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.provider.ContactsContract;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import java.io.BufferedInputStream;
import java.io.InputStream;
import java.util.List;
public class myAdapter extends RecyclerView.Adapter<ListViewHolder>{
private List<ListItems> listItemsList;
private Context mContext;
private int focusedItem = 0;
public myAdapter(Context context){
mContext = context;
ContentResolver cr = mContext.getContentResolver();
Cursor cur = cr.query(ContactsContract.Contacts.CONTENT_URI, null, null, null, null);
String name;
String phone = null;
String image_uri = "";
ListItems listItems;
int i = 1;
if (cur.getCount() > 0) {
while (cur.moveToNext()) {
if(i == 1){
cur.moveToFirst();
i++;
}
String id = cur.getString(cur
.getColumnIndex(ContactsContract.Contacts._ID));
name = cur
.getString(cur
.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
image_uri = cur
.getString(cur
.getColumnIndex(ContactsContract.CommonDataKinds.Phone.PHOTO_URI));
Cursor pCur = cr.query(
ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
null,
ContactsContract.CommonDataKinds.Phone.CONTACT_ID
+ " = ?", new String[]{id}, null);
if (pCur.moveToNext()) {
phone = pCur
.getString(pCur
.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
System.out.println("Name: "+ name + "phone: " + phone);
}
pCur.close();
listItems = new ListItems(name,phone,image_uri);
listItemsList.add(listItems);
}
cur.close();
}
}
#Override
public ListViewHolder onCreateViewHolder(ViewGroup viewGroup, int position) {
Context context = viewGroup.getContext();
LayoutInflater layoutInflater = LayoutInflater.from(context);
View v = layoutInflater.inflate(R.layout.list_row,null);
//View v = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.list_row,null);
ListViewHolder holder = new ListViewHolder(v);
holder.relativeLayout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
}
});
return holder;
}
#Override
public void onBindViewHolder(ListViewHolder holder, int position) {
ListItems listItems = listItemsList.get(position);
TextView contact_name = holder.contactname;
TextView contact_num = holder.contactnum;
ImageView contact_image = holder.contactimage;
contact_name.setText(listItems.getContactname());
contact_num.setText(listItems.getContactnum());
Uri myuri = Uri.parse(listItems.getThumbnail());
InputStream photo_stream = ContactsContract.Contacts.openContactPhotoInputStream(mContext.getContentResolver(),myuri);
BufferedInputStream buf =new BufferedInputStream(photo_stream);
Bitmap my_btmp = BitmapFactory.decodeStream(buf);
contact_image.setImageBitmap(my_btmp);
}
#Override
public int getItemCount() {
return listItemsList.size();
}
}
ListViewHolder.java
package com.example.anubh.contactsearch;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
public class ListViewHolder extends RecyclerView.ViewHolder {
protected ImageView contactimage;
protected TextView contactname,contactnum;
protected RelativeLayout relativeLayout;
public ListViewHolder(View view){
super(view);
contactimage = (ImageView)view.findViewById(R.id.contactimage);
contactname = (TextView) view.findViewById(R.id.contactname);
contactnum = (TextView) view.findViewById(R.id.contactno);
relativeLayout = (RelativeLayout) view.findViewById(R.id.relativeLayout);
view.setClickable(false);
}
}
ListItems.java
package com.example.anubh.contactsearch;
public class ListItems {
private String Contactname,contactnum,thumbnail;
public ListItems(String name,String number,String imageuri){
this.Contactname = name;
this.contactnum = number;
this.thumbnail = imageuri;
}
public String getContactname() {
return Contactname;
}
public void setContactname(String contactname) {
Contactname = contactname;
}
public String getContactnum() {
return contactnum;
}
public void setContactnum(String contactnum) {
this.contactnum = contactnum;
}
public String getThumbnail() {
return thumbnail;
}
public void setThumbnail(String thumbnail) {
this.thumbnail = thumbnail;
}
}
Manifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.anubh.contactsearch">
<uses-permission android:name="android.permission.READ_CONTACTS" />
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.Main" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
<meta-data android:name="android.app.searchable"
android:resource="#xml/searchable"/>
</activity>
</application>
</manifest>
Add this line to "myAdapter" constructor.
listItemsList = new ArrayList<>();
I know this is an old thread, but I have checked your code because I am doing something similar. I saw you had problems with RecyclerView not showing anything, and the problem might be in how you handle your ListItems object.
First of all, you've forgotten about the layout manager in MainActivity.java:
recyclerView.setLayoutManager(new LinearLayoutManager(getApplicationContext()));
Second, you have no checks to determine if a user even has an image, because in case it doesn't, you will receive a null pointer exception error. When you store a null value in your thumbnail variable, later trying to access it in the adapter
Uri myuri = Uri.parse(listItems.getThumbnail());
there is a simple check missing, for example
if (listItems.getThumbnail() != null) {
Uri myuri = Uri.parse(listItems.getThumbnail());
InputStream photo_stream = ContactsContract.Contacts.openContactPhotoInputStream(mContext.getContentResolver(),myuri);
BufferedInputStream buf =new BufferedInputStream(photo_stream);
Bitmap my_btmp = BitmapFactory.decodeStream(buf);
contact_image.setImageBitmap(my_btmp);
} else {
// Find an alternative method, like displaying custom ImageView with name initials
}
Finally, I would like to point out a redundant if statement in adapter's constructor
if(i == 1){
cur.moveToFirst();
i++;
}
There is no need to make an additional check, you can simply say
cur.moveToFirst();

Error: Unused Import Statement - import android.widget.AdapterView.OnItemClickListener; & import android.content.Context;

I have made a simple app which saves and displays bookmarks.
The view bookmarks activity is called by clicking on a menu item in the main activity.
The problem is that when I click the option to view bookmarks stored in view bookmarks Activity, my app crashes.
The problem, I think, is with the bookmark Activity because I have an unused import statement AdapterView.OnItemClickListener & content.Context.
How do I solve this issue?
PS: when I click the option in the main Activity to save a bookmark by launching the save bookmark Activity, it works perfectly.
Here is my code:
BookmarkPage.class
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
import java.util.ArrayList;
public class BookmarkPage extends Activity {
public final static String EXTRA_MESSAGE = "MESSAGE";
private ListView obj;
DBHelper mydb;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.bookmark_page);
mydb = new DBHelper(this);
ArrayList array_list = mydb.getAllBookmarks();
ArrayAdapter arrayAdapter=new ArrayAdapter(this,android.R.layout.simple_list_item_1, array_list);
obj = (ListView)findViewById(R.id.listView1);
obj.setAdapter(arrayAdapter);
obj.setOnItemClickListener(new AdapterView.OnItemClickListener(){
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,long arg3) {
// TODO Auto-generated method stub
int id_To_Search = arg2 + 1;
Bundle dataBundle = new Bundle();
dataBundle.putInt("id", id_To_Search);
Intent intent = new Intent(getApplicationContext(),DisplayBookmarks.class);
intent.putExtras(dataBundle);
startActivity(intent);
}
});
}
public boolean onKeyDown(int keycode, KeyEvent event) {
if (keycode == KeyEvent.KEYCODE_BACK) {
moveTaskToBack(true);
}
return super.onKeyDown(keycode, event);
}
}
bookmark_page.xml
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context=".BookmarkPage">
<TextView
android:id="#+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:text="Bookmarks"
android:textSize="30sp" />
<ListView
android:id="#+id/listView1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/textView">
</ListView>
</RelativeLayout>
Logcat:
OpenGL ES Shader Compiler Version: E031.25.03.00
Build Date: 12/04/14 Thu
Local Branch:
Remote Branch: quic/LA.BF.1.1_rb1.14
Local Patches: NONE
Reconstruct Branch: AU_LINUX_ANDROID_LA.BF.1.1_RB1.05.00.00.002.030 + NOTHING
10-03 18:10:35.793 18581-18642/com.carsaleindiaofficial.csitestapp W/cr.media﹕ Requires BLUETOOTH permission
10-03 18:10:35.830 18581-18581/com.carsaleindiaofficial.csitestapp E/libEGL﹕ validate_display:255 error 3008 (EGL_BAD_DISPLAY)
10-03 18:10:35.890 18581-18581/com.carsaleindiaofficial.csitestapp I/art﹕ Rejecting re-init on previously-failed class java.lang.Class<com.android.webview.chromium.FloatingSelectActionModeCallback>
10-03 18:10:35.891 18581-18581/com.carsaleindiaofficial.csitestapp I/art﹕ Rejecting re-init on previously-failed class java.lang.Class<com.android.webview.chromium.FloatingSelectActionModeCallback>
10-03 18:10:35.922 18581-18581/com.carsaleindiaofficial.csitestapp I/art﹕ Rejecting re-init on previously-failed class java.lang.Class<com.android.webview.chromium.WebViewContentsClientAdapter$WebResourceErrorImpl>
10-03 18:10:35.922 18581-18581/com.carsaleindiaofficial.csitestapp I/art﹕ Rejecting re-init on previously-failed class java.lang.Class<com.android.webview.chromium.WebViewContentsClientAdapter$WebResourceErrorImpl>
10-03 18:10:36.276 18581-18581/com.carsaleindiaofficial.csitestapp W/art﹕ Attempt to remove local handle scope entry from IRT, ignoring
10-03 18:10:36.318 18581-18581/com.carsaleindiaofficial.csitestapp W/AwContents﹕ onDetachedFromWindow called when already detached. Ignoring
10-03 18:10:36.836 18581-18681/com.carsaleindiaofficial.csitestapp D/OpenGLRenderer﹕ Render dirty regions requested: true
10-03 18:10:36.902 18581-18581/com.carsaleindiaofficial.csitestapp D/Atlas﹕ Validating map...
10-03 18:10:36.944 18581-18639/com.carsaleindiaofficial.csitestapp W/chromium﹕ [WARNING:data_reduction_proxy_config.cc(630)] SPDY proxy OFF at startup
10-03 18:10:37.192 18581-18681/com.carsaleindiaofficial.csitestapp I/OpenGLRenderer﹕ Initialized EGL, version 1.4
10-03 18:10:37.201 18581-18681/com.carsaleindiaofficial.csitestapp D/OpenGLRenderer﹕ Enabling debug mode 0
10-03 18:10:38.109 18581-18581/com.carsaleindiaofficial.csitestapp I/Choreographer﹕ Skipped 49 frames! The application may be doing too much work on its main thread.
10-03 18:10:38.213 18581-18581/com.carsaleindiaofficial.csitestapp I/progressBar﹕ Visible
10-03 18:10:38.222 18581-18596/com.carsaleindiaofficial.csitestapp I/art﹕ Background sticky concurrent mark sweep GC freed 10653(792KB) AllocSpace objects, 6(92KB) LOS objects, 12% free, 6MB/7MB, paused 1.507ms total 130.800ms
10-03 18:10:38.894 18581-18581/com.carsaleindiaofficial.csitestapp W/cr.BindingManager﹕ Cannot call determinedVisibility() - never saw a connection for the pid: 18581
10-03 18:10:41.925 18581-18596/com.carsaleindiaofficial.csitestapp I/art﹕ Background partial concurrent mark sweep GC freed 12880(607KB) AllocSpace objects, 1(39KB) LOS objects, 40% free, 7MB/11MB, paused 1.053ms total 158.419ms
10-03 18:10:42.812 18581-18581/com.carsaleindiaofficial.csitestapp W/cr.BindingManager﹕ Cannot call determinedVisibility() - never saw a connection for the pid: 18581
10-03 18:10:43.549 18581-18581/com.carsaleindiaofficial.csitestapp W/cr.BindingManager﹕ Cannot call determinedVisibility() - never saw a connection for the pid: 18581
Problem Starts after progressbar:Gone (i.e when I press the view saved bookmarks option)
10-03 21:13:12.096 18489-18489/com.carsaleindiaofficial.csitestapp I/pageFinished﹕ yesss
10-03 21:13:12.353 18489-18489/com.carsaleindiaofficial.csitestapp I/progressBar﹕ Gone
10-03 21:13:26.413 18489-18489/com.carsaleindiaofficial.csitestapp I/Choreographer﹕ Skipped 64 frames! The application may be doing too much work on its main thread.
10-03 21:13:28.701 18489-18489/com.carsaleindiaofficial.csitestapp W/art﹕ Before Android 4.1, method int android.support.v7.internal.widget.ListViewCompat.lookForSelectablePosition(int, boolean) would have incorrectly overridden the package-private method in android.widget.ListView
10-03 21:13:30.289 18489-18489/com.carsaleindiaofficial.csitestapp I/Choreographer﹕ Skipped 129 frames! The application may be doing too much work on its main thread.
10-03 21:13:31.604 18489-18489/com.carsaleindiaofficial.csitestapp I/Choreographer﹕ Skipped 78 frames! The application may be doing too much work on its main thread.
10-03 21:13:33.328 18489-18489/com.carsaleindiaofficial.csitestapp I/Choreographer﹕ Skipped 80 frames! The application may be doing too much work on its main thread.
10-03 21:13:35.714 18489-18489/com.carsaleindiaofficial.csitestapp I/Choreographer﹕ Skipped 38 frames! The application may be doing too much work on its main thread.
10-03 21:13:36.532 18489-18489/com.carsaleindiaofficial.csitestapp I/Choreographer﹕ Skipped 44 frames! The application may be doing too much work on its main thread.
10-03 21:13:37.719 18489-18489/com.carsaleindiaofficial.csitestapp E/CursorWindow﹕ Failed to read row 0, column -1 from a CursorWindow which has 9 rows, 2 columns.
10-03 21:13:37.777 18489-18489/com.carsaleindiaofficial.csitestapp D/AndroidRuntime﹕ Shutting down VM
10-03 21:13:37.892 18489-18489/com.carsaleindiaofficial.csitestapp E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.carsaleindiaofficial.csitestapp, PID: 18489
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.carsaleindiaofficial.csitestapp/com.carsaleindiaofficial.csitestapp.BookmarkPage}: java.lang.IllegalStateException: Couldn't read row 0, col -1 from CursorWindow. Make sure the Cursor is initialized correctly before accessing data from it.
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2314)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2388)
at android.app.ActivityThread.access$800(ActivityThread.java:148)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1292)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5312)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:901)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:696)
Caused by: java.lang.IllegalStateException: Couldn't read row 0, col -1 from CursorWindow. Make sure the Cursor is initialized correctly before accessing data from it.
at android.database.CursorWindow.nativeGetString(Native Method)
at android.database.CursorWindow.getString(CursorWindow.java:438)
at android.database.AbstractWindowedCursor.getString(AbstractWindowedCursor.java:51)
at com.carsaleindiaofficial.csitestapp.DBHelper.getAllBookmarks(DBHelper.java:90)
at com.carsaleindiaofficial.csitestapp.BookmarkPage.onCreate(BookmarkPage.java:32)
at android.app.Activity.performCreate(Activity.java:5953)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1128)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2267)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2388)
at android.app.ActivityThread.access$800(ActivityThread.java:148)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1292)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5312)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:901)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:696)
10-03 21:13:43.601 18489-18489/com.carsaleindiaofficial.csitestapp I/Process﹕ Sending signal. PID: 18489 SIG: 9
My database: DBHelper.class
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Hashtable;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.DatabaseUtils;
import android.database.sqlite.SQLiteOpenHelper;
import android.database.sqlite.SQLiteDatabase;
public class DBHelper extends SQLiteOpenHelper {
public static final String DATABASE_NAME = "MyDBName.db";
public static final String BOOKMARKS_TABLE_NAME = "bookmarks";
public static final String BOOKMARKS_COLUMN_ID = "id";
public static final String BOOKMARKS_COLUMN_NAME = "bmtitle";
private HashMap hp;
public DBHelper(Context context)
{
super(context, DATABASE_NAME , null, 1);
}
#Override
public void onCreate(SQLiteDatabase db) {
// TODO Auto-generated method stub
db.execSQL(
"create table bookmarks " +
"(id integer primary key, bmtitle text)"
);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// TODO Auto-generated method stub
db.execSQL("DROP TABLE IF EXISTS bookmarks");
onCreate(db);
}
public boolean insertBookmark (String title)
{
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put("dbtitle", title);
db.insert("bookmarks", null, contentValues);
return true;
}
public Cursor getData(int id){
SQLiteDatabase db = this.getReadableDatabase();
Cursor res = db.rawQuery( "select * from bookmarks where id="+id+"", null );
return res;
}
public int numberOfRows(){
SQLiteDatabase db = this.getReadableDatabase();
int numRows = (int) DatabaseUtils.queryNumEntries(db, BOOKMARKS_TABLE_NAME);
return numRows;
}
public boolean updateBookmark (Integer id, String title)
{
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put("name", title);
db.update("bookmarks", contentValues, "id = ? ", new String[] { Integer.toString(id) } );
return true;
}
public Integer deleteBookmark (Integer id)
{
SQLiteDatabase db = this.getWritableDatabase();
return db.delete("bookmarks",
"id = ? ",
new String[] { Integer.toString(id) });
}
public ArrayList<String> getAllBookmarks()
{
ArrayList<String> array_list = new ArrayList<String>();
//hp = new HashMap();
SQLiteDatabase db = this.getReadableDatabase();
Cursor res = db.rawQuery( "select * from bookmarks", null );
res.moveToFirst();
while(res.isAfterLast() == false){
array_list.add(res.getString(res.getColumnIndex(BOOKMARKS_COLUMN_NAME)));
res.moveToNext();
}
return array_list;
}
}
MainActivity.class
import android.annotation.SuppressLint;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ImageView;
import android.widget.ProgressBar;
#SuppressLint("SetJavaScriptEnabled")
public class MainActivity extends AppCompatActivity {
private WebView view;
ProgressBar progressBar;
ImageView im;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getSupportActionBar().setDisplayShowHomeEnabled(true);
getSupportActionBar().setLogo(R.drawable.ic_launcher);
getSupportActionBar().setDisplayUseLogoEnabled(true);
setContentView(R.layout.activity_main);
progressBar = (ProgressBar) this.findViewById(R.id.progressBar1);
im = (ImageView) this.findViewById(R.id.imageView2);
String url = "http://www.carsaleindiaofficial.com/?m=1";
view = (WebView) this.findViewById(R.id.webView);
view.setWebViewClient(new MyWebViewClient());
view.getSettings().setJavaScriptEnabled(true);
view.getSettings().setDomStorageEnabled(true);
view.loadUrl(url);
}
public class MyWebViewClient extends WebViewClient {
#Override
public void onPageFinished(WebView view, String url) {
super.onPageFinished(view, url);
Log.i("pageFinished", "yesss");
progressBar.setVisibility(View.GONE);
im.setVisibility(View.GONE);
Log.i("progressBar", "Gone");
}
#Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
progressBar.setVisibility(View.VISIBLE);
Log.i("progressBar", "Visible");
super.onPageStarted(view, url, favicon);
}
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
if(Uri.parse(url).getHost().endsWith("carsaleindiaofficial.com")) {
Log.i("ShldOvrideUrl", "CSI");
return false;
}
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
view.getContext().startActivity(intent);
Log.i("ShldOvrideUrl", "OtherSite");
return true;
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item){
super.onOptionsItemSelected(item);
switch(item.getItemId())
{
case R.id.add_bookmark:
Bundle dataBundle = new Bundle();
dataBundle.putInt("id", 0);
Log.i("addBookmark", "loadingAddBookmark");
Intent intent = new Intent(getApplicationContext(),DisplayBookmarks.class);
intent.putExtras(dataBundle);
startActivity(intent);
return true;
case R.id.show_bookmark:
Log.i("showBookmark", "loadingShowBookmark");
Intent intent2 = new Intent(getApplicationContext(),BookmarkPage.class);
startActivity(intent2);
return true;
case R.id.action_reload:
Log.i("actionReload", "ReloadingURL");
view.loadUrl(view.getUrl());
default:
return super.onOptionsItemSelected(item);
}
}
#Override
public void onBackPressed() {
if (view.canGoBack()) {
view.goBack();
} else {
super.onBackPressed();
}
}
}
Here's your error:
Failed to read row 0, column -1 from a CursorWindow which has 9 rows, 2 columns. ... Caused by: java.lang.IllegalStateException: Couldn't read row 0, col -1 from CursorWindow. Make sure the Cursor is initialized correctly before accessing data from it.
This is because you create this table:
#Override
public void onCreate(SQLiteDatabase db) {
// TODO Auto-generated method stub
db.execSQL(
"create table bookmarks " +
"(id integer primary key, dbtitle text)"
);
}
Then you try to access a non existing column:
while(res.isAfterLast() == false){
array_list.add(res.getString(res.getColumnIndex(BOOKMARKS_COLUMN_NAME)));
res.moveToNext();
}
Which is defined as a string constant:
public static final String BOOKMARKS_COLUMN_NAME = "bmtitle";
But it's not created as a table column.
column -1 says that there's no column called bmtitle in your table.
And it's right, because, instead, there is a column named dbtitle.
Quick fix:
Simply change
public static final String BOOKMARKS_COLUMN_NAME = "bmtitle";
to
public static final String BOOKMARKS_COLUMN_NAME = "dbtitle";

Categories

Resources