Hello I'm working on an application that is going to be android launcher there are three different screens in this launcher the first screen is a bookshelf that is supposed to import and Show all books in the SD card place on the device the second is a calculator (works just fine!) Third is a Homework page where you can make google drive docs and flashcards (also works fine!!) I get no errors when I run my code the app automatically crashes when it launches on my device and on the emulator.
Heres my Logcat:
11-23 15:05:06.314: E/SurfaceFlinger(323): ro.sf.lcd_density must be defined as a build property
11-23 15:05:15.084: E/Trace(3807): error opening trace file: No such file or directory (2)
11-23 15:05:15.254: E/AndroidRuntime(3807): FATAL EXCEPTION: main
11-23 15:05:15.254: E/AndroidRuntime(3807): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.d4a.tobias/it.gmariotti.android.examples.googleaccount.MainFrag}: java.lang.NullPointerException
11-23 15:05:15.254: E/AndroidRuntime(3807): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2180)
11-23 15:05:15.254: E/AndroidRuntime(3807): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2230)
11-23 15:05:15.254: E/AndroidRuntime(3807): at android.app.ActivityThread.access$600(ActivityThread.java:141)
11-23 15:05:15.254: E/AndroidRuntime(3807): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1234)
11-23 15:05:15.254: E/AndroidRuntime(3807): at android.os.Handler.dispatchMessage(Handler.java:99)
11-23 15:05:15.254: E/AndroidRuntime(3807): at android.os.Looper.loop(Looper.java:137)
11-23 15:05:15.254: E/AndroidRuntime(3807): at android.app.ActivityThread.main(ActivityThread.java:5041)
11-23 15:05:15.254: E/AndroidRuntime(3807): at java.lang.reflect.Method.invokeNative(Native Method)
11-23 15:05:15.254: E/AndroidRuntime(3807): at java.lang.reflect.Method.invoke(Method.java:511)
11-23 15:05:15.254: E/AndroidRuntime(3807): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
11-23 15:05:15.254: E/AndroidRuntime(3807): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
11-23 15:05:15.254: E/AndroidRuntime(3807): at dalvik.system.NativeStart.main(Native Method)
11-23 15:05:15.254: E/AndroidRuntime(3807): Caused by: java.lang.NullPointerException
11-23 15:05:15.254: E/AndroidRuntime(3807): at com.sibext.android_shelf.adapter.ShelfAdapter.setToListView(ShelfAdapter.java:70)
11-23 15:05:15.254: E/AndroidRuntime(3807): at it.gmariotti.android.examples.googleaccount.MainFrag.onCreate(MainFrag.java:78)
11-23 15:05:15.254: E/AndroidRuntime(3807): at android.app.Activity.performCreate(Activity.java:5104)
11-23 15:05:15.254: E/AndroidRuntime(3807): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1080)
11-23 15:05:15.254: E/AndroidRuntime(3807): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2144)
11-23 15:05:15.254: E/AndroidRuntime(3807): ... 11 more
11-23 15:05:15.354: E/SurfaceFlinger(323): ro.sf.lcd_density must be defined as a build property
11-23 15:05:15.824: E/SurfaceFlinger(323): ro.sf.lcd_density must be defined as a build property
11-23 15:07:05.354: E/SurfaceFlinger(323): ro.sf.lcd_density must be defined as a build property
Heres MainFrag.java:
package it.gmariotti.android.examples.googleaccount;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Arrays;
import java.util.List;
import android.content.Context;
import android.content.Intent;
import android.content.res.AssetManager;
import android.os.Bundle;
import android.os.Environment;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.widget.ListView;
import android.widget.Toast;
import com.d4a.tobias.R;
import com.sibext.android_shelf.ImportBooks;
import com.sibext.android_shelf.adapter.ShelfAdapter;
public class MainFrag extends FragmentActivity{
private MyAdapter mAdapter;
private ViewPager mPager;
//Shelf
private static final String TARGET_DIRECTORY = "mnt/sdcard/shelf/";
private ListView list;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.mainfrag);
mAdapter = new MyAdapter(getSupportFragmentManager());
mPager = (ViewPager) findViewById(R.id.pager);
mPager.setAdapter(mAdapter);
// TitlePageIndicator titleIndicator = (TitlePageIndicator) findViewById(R.id.titles);
// titleIndicator.setViewPager(mPager);
// pts=(PagerTitleStrip)findViewById(R.id.pager_title_strip);
//Shelf
File dir = new File(TARGET_DIRECTORY);
if(!dir.exists()){
dir.mkdirs();
//past here
addBooksFromAssetsToCard();
}else{
String files[] = dir.list();
if(files.length == 0){
//past here
addBooksFromAssetsToCard();
}
}
list = (ListView)findViewById(R.id.list);
ShelfAdapter adapter = new ShelfAdapter(this, TARGET_DIRECTORY);
adapter.setToListView(list);
}
public static class MyAdapter extends FragmentPagerAdapter {
String arr[]={"Calculator","Books","Homework"};
public MyAdapter(FragmentManager fm) {
super(fm);
}
#Override
public CharSequence getPageTitle(int position) {
// TODO Auto-generated method stub
return arr[position];
}
#Override
public int getCount() {
return arr.length;
}
#Override
public Fragment getItem(int position) {
switch (position) {
case 0:
return new Calculator();
case 1:
return new Book();
case 2:
return new Homework();
default:
return null;
}
}
}
//Shelf
public void addBooksFromAssetsToCard(){
List<String> books;
try {
books = getBooksFromAsset(getApplicationContext());
for(String book : books){
copyFromAssets(book);
}
} catch (Exception e) {
}
}
public List<String> getBooksFromAsset(Context ctx) throws Exception
{
AssetManager assetManager =ctx.getAssets();
String[] files = assetManager.list("books");
List<String> it=Arrays.asList(files);
return it;
}
public void copyFromAssets(String book)
{
AssetManager assetManager = getAssets();
String[] files = null;
InputStream in = null;
OutputStream out = null;
//String filename = "filename.ext";
try
{
in = assetManager.open("books/"+book);
out = new FileOutputStream(Environment.getExternalStorageDirectory()+File.separator+"/shelf/"+book);
Log.d("Copying...", ""+book);
copyFile(in, out);
in.close();
in = null;
out.flush();
out.close();
out = null;
}
catch(Exception e)
{
Log.e("tag", "Failed to copy asset file: " + book, e);
}
}
public void copyFile(InputStream in, OutputStream out) throws Exception
{
byte[] buffer = new byte[1024];
int read;
while((read = in.read(buffer)) != -1)
{
out.write(buffer, 0, read);
}
Log.d("Copy_State", "Done...");
}
public void onImportClicked(View v){
Toast.makeText(getApplicationContext(), "Please wait...", Toast.LENGTH_LONG).show();
Intent in = new Intent(getApplicationContext(), ImportBooks.class);
startActivity(in);
}
}
EDIT ADDED Shelf Adapter.java :
package com.sibext.android_shelf.adapter;
import java.io.File;
import java.util.ArrayList;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.res.Configuration;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.net.Uri;
import android.os.AsyncTask;
import android.util.SparseArray;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.LinearLayout.LayoutParams;
import android.widget.ListView;
import android.widget.Toast;
import com.d4a.tobias.R;
import com.sibext.android_shelf.MainActivity;
import com.sibext.android_shelf.shelf.ShelfItem;
public class ShelfAdapter extends BaseAdapter {
private static final int ROW_COUNT_DEFAULT = 2;
private static final int ROW_COUNT_LAND_DEFAULT = 4;
private static final int ROW_HEIGHT_DEFAULT = 150;
private Context context;
private int rowCount = ROW_COUNT_DEFAULT;
private int rowCountLand = ROW_COUNT_LAND_DEFAULT;
private int rowHeight = ROW_HEIGHT_DEFAULT;
private SparseArray<LoadPreviewTask> taskPool;
private ArrayList<ShelfItem> items;
String PATH;
ShelfItem item;
public ShelfAdapter(Context context, String targetDir) {
this.context = context;
items = new ArrayList<ShelfItem>();
taskPool = new SparseArray<ShelfAdapter.LoadPreviewTask>();
if (targetDir == null || context == null) {
throw new NullPointerException("ShelfAdapter: wrong paramenters - " +
(targetDir == null ? "Target directory " : "Context ") + "is null");
}
File dir = new File(targetDir);
if(dir.exists() && dir.isDirectory()){
for(File f : dir.listFiles()){
if(f != null && f.getName().endsWith(".pdf")){
items.add(new ShelfItem(f));
}
}
}
}
public void setToListView(ListView list){
list.setDividerHeight(0);
list.setAdapter(this);
}
public void setRowCount(int rowCount, int rowCountLand) {
this.rowCount = rowCount;
this.rowCountLand = rowCountLand;
}
public void setRowHeight(int rowHeight) {
this.rowHeight = rowHeight;
}
#Override
public int getCount() {
int sub = getSubItemsCount();
return (int)(sub/getRowCount()) + (sub%getRowCount() == 0 ? 0 : 1);
}
public int getSubItemsCount(){
return items.size();
}
#Override
public ShelfItem getItem(int position) {
return items.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if(convertView == null){
holder = new ViewHolder();
convertView = View.inflate(context, R.layout.shelf_row, null);
AbsListView.LayoutParams itemParams = new AbsListView.LayoutParams(
AbsListView.LayoutParams.MATCH_PARENT, rowHeight);
convertView.setLayoutParams(itemParams);
LinearLayout.LayoutParams subItemParams = getSubViewParams();
for(int i = 0; i < getRowCount(); i++){
View sub = getSubView(getSubPosition(position, i), null);
sub.setLayoutParams(subItemParams);
((ViewGroup)convertView).addView(sub);
holder.subViews.add(sub);
}
convertView.setTag(holder);
} else {
holder = (ViewHolder)convertView.getTag();
for(int i = 0; i < holder.subViews.size(); i++){
getSubView(getSubPosition(position, i), holder.subViews.get(i));
}
}
return convertView;
}
public View getSubView(final int position, View convertView){
final SubViewHolder holder;
if(convertView == null){
convertView = View.inflate(context, R.layout.shelf_item, null);
holder = new SubViewHolder();
holder.img = (ImageView)convertView.findViewById(R.id.shelf_item_image);
convertView.setTag(holder);
} else {
holder = (SubViewHolder)convertView.getTag();
}
if(position >= getSubItemsCount()){
holder.img.setImageBitmap(null);
return convertView;
}
item = getItem(position);
PATH = item.getFile().getAbsolutePath();
Bitmap preview = item.getPreviewFromSD();
if(preview != null){
holder.img.setImageBitmap(preview);
} else {
holder.img.setImageResource(R.drawable.ic_launcher);
LoadPreviewTask task = taskPool.get(holder.hashCode());
if (task != null) {
task.cancel(true);
taskPool.remove(holder.hashCode());
task = null;
}
task = new LoadPreviewTask(holder, rowHeight);
taskPool.put(holder.hashCode(), task);
task.execute(item);
}
holder.img.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
final ShelfItem si = items.get(position);
/*Toast.makeText(context, "Item #" + position+"\n"+si.getFile().getAbsolutePath(), Toast.LENGTH_SHORT).show();
*/
final CharSequence[] items = {"View", "Delete"};
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("Please choose:");
builder.setItems(items, new DialogInterface.OnClickListener() {
//Toast.makeText(getApplicationContext(), ""+items[0], Toast.LENGTH_SHORT).show();
public void onClick(DialogInterface dialog, int index) {
if(index == 0){
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(Uri.fromFile(si.getFile()),"application/pdf");
intent.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
context.startActivity(intent);
}else if(index == 1){
File file = new File(si.getFile().getAbsoluteFile().toString());
boolean deleteStatus = file.delete();
if(deleteStatus){
Toast.makeText(context, "Deleted Successfully...", Toast.LENGTH_SHORT).show();
Intent in = new Intent(context, MainActivity.class);
context.startActivity(in);
}else{
Toast.makeText(context, "Unable to delete...", Toast.LENGTH_SHORT).show();
}
}
}
});
AlertDialog alert = builder.create();
alert.show();
}
});
return convertView;
}
private int getSubPosition(int listItemPosition, int offset){
return listItemPosition * getRowCount() + offset;
}
private LinearLayout.LayoutParams getSubViewParams(){
LinearLayout.LayoutParams p = new LayoutParams(0, LayoutParams.MATCH_PARENT);
p.weight = 1f;
return p;
}
private int getRowCount() {
return context.getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT
? rowCount : rowCountLand;
}
private static class ViewHolder{
public ArrayList<View> subViews;
public ViewHolder() {
this.subViews = new ArrayList<View>();
}
}
private static class SubViewHolder{
public ImageView img;
}
private class LoadPreviewTask extends AsyncTask<ShelfItem, Void, Bitmap>{
private SubViewHolder holder;
private int rowHeight;
public LoadPreviewTask(SubViewHolder holder, int rowHeight) {
super();
this.holder = holder;
this.rowHeight = rowHeight;
}
#Override
protected Bitmap doInBackground(ShelfItem... params) {
ShelfItem item = (ShelfItem)params[0];
Bitmap preview = item.getPreview(rowHeight);
item.savePreview(preview);
return preview;
}
#Override
protected void onPostExecute(final Bitmap result) {
if(isCancelled()){
holder = null;
return;
}
holder.img.setImageBitmap(result);
taskPool.remove(holder.hashCode());
}
}
}
I'm still fairly new to Android so please don’t judge and any help will be greatly appreciated
Thanks in advance
list = (ListView)findViewById(R.id.list); returns null because your list is not created yet. Override the onViewCreated() and put your code in there.
Your problem is here: adapter.setToListView(list); should be something like: list.setAdapter(...) but you have another errors on ShelfAdapter.java, can you copy what you have written from line 65 to line 70?
Related
I'm testing the new support library leanback to design apps for TV, and i have a error ever android try to inflate the BrowseFragment and it throws this exception and don't know how to solve it. Thank you so much for your help.
Error -
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.directsportsnetwork.tv/com.directsportsnetwork.tv.ui.TeamSclActivity}: android.view.InflateException: Binary XML file line #67 in com.directsportsnetwork.tv:layout/activity_teamscl: Binary XML file line #24 in com.directsportsnetwork.tv:layout/lb_browse_fragment: Binary XML file line #24 in com.directsportsnetwork.tv:layout/lb_browse_fragment: Error inflating class androidx.leanback.widget.BrowseFrameLayout
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3449)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3601)
at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:85)
at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135)
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2066)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:223)
at android.app.ActivityThread.main(ActivityThread.java:7656)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:592)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:947)
Caused by: android.view.InflateException: Binary XML file line #67 in com.directsportsnetwork.tv:layout/activity_teamscl: Binary XML file line #24 in com.directsportsnetwork.tv:layout/lb_browse_fragment: Binary XML file line #24 in com.directsportsnetwork.tv:layout/lb_browse_fragment: Error inflating class androidx.leanback.widget.BrowseFrameLayout
Caused by: android.view.InflateException: Binary XML file line #24 in com.directsportsnetwork.tv:layout/lb_browse_fragment: Binary XML file line #24 in com.directsportsnetwork.tv:layout/lb_browse_fragment: Error inflating class androidx.leanback.widget.BrowseFrameLayout
Caused by: android.view.InflateException: Binary XML file line #24 in com.directsportsnetwork.tv:layout/lb_browse_fragment: Error inflating class androidx.leanback.widget.BrowseFrameLayout
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.Object java.lang.reflect.Field.get(java.lang.Object)' on a null object reference
at uk.co.chrisjenx.calligraphy.ReflectionUtils.getValue(ReflectionUtils.java:29)
at uk.co.chrisjenx.calligraphy.CalligraphyLayoutInflater.createCustomViewInternal(CalligraphyLayoutInflater.java:203)
at uk.co.chrisjenx.calligraphy.CalligraphyLayoutInflater.access$000(CalligraphyLayoutInflater.java:20)
at uk.co.chrisjenx.calligraphy.CalligraphyLayoutInflater$PrivateWrapperFactory2.onCreateView(CalligraphyLayoutInflater.java:302)
at android.view.LayoutInflater$FactoryMerger.onCreateView(LayoutInflater.java:237)
at android.view.LayoutInflater.tryCreateView(LayoutInflater.java:1067)
at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:995)
at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:959)
at android.view.LayoutInflater.rInflate(LayoutInflater.java:1121)
at android.view.LayoutInflater.rInflateChildren(LayoutInflater.java:1082)
at android.view.LayoutInflater.inflate(LayoutInflater.java:680)
at uk.co.chrisjenx.calligraphy.CalligraphyLayoutInflater.inflate(CalligraphyLayoutInflater.java:60)
at android.view.LayoutInflater.inflate(LayoutInflater.java:532)
at androidx.leanback.app.BrowseFragment.onCreateView(BrowseFragment.java:1318)
at android.app.Fragment.performCreateView(Fragment.java:2505)
at android.app.FragmentManagerImpl.ensureInflatedFragmentView(FragmentManager.java:1491)
at android.app.FragmentManagerImpl.moveToState(FragmentManager.java:1274)
at android.app.FragmentManagerImpl.moveToState(FragmentManager.java:1486)
at android.app.FragmentManagerImpl.addFragment(FragmentManager.java:1728)
E/AndroidRuntime: at android.app.FragmentManagerImpl.onCreateView(FragmentManager.java:3562)
at android.app.FragmentController.onCreateView(FragmentController.java:104)
at android.app.Activity.onCreateView(Activity.java:7112)
at androidx.fragment.app.FragmentActivity.onCreateView(FragmentActivity.java:229)
at uk.co.chrisjenx.calligraphy.CalligraphyLayoutInflater$PrivateWrapperFactory2.onCreateView(CalligraphyLayoutInflater.java:303)
at android.view.LayoutInflater$FactoryMerger.onCreateView(LayoutInflater.java:237)
at android.view.LayoutInflater.tryCreateView(LayoutInflater.java:1067)
at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:995)
at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:959)
at android.view.LayoutInflater.rInflate(LayoutInflater.java:1121)
at android.view.LayoutInflater.rInflateChildren(LayoutInflater.java:1082)
at android.view.LayoutInflater.inflate(LayoutInflater.java:680)
at uk.co.chrisjenx.calligraphy.CalligraphyLayoutInflater.inflate(CalligraphyLayoutInflater.java:60)
at android.view.LayoutInflater.inflate(LayoutInflater.java:532)
at android.view.LayoutInflater.inflate(LayoutInflater.java:479)
at android.transition.Scene.enter(Scene.java:182)
at com.android.internal.policy.PhoneWindow.transitionTo(PhoneWindow.java:522)
at com.android.internal.policy.PhoneWindow.setContentView(PhoneWindow.java:453)
at android.app.Activity.setContentView(Activity.java:3468)
at androidx.activity.ComponentActivity.setContentView(ComponentActivity.java:448)
at com.directsportsnetwork.tv.ui.TeamSclActivity.onCreate(TeamSclActivity.java:55)
at android.app.Activity.performCreate(Activity.java:8000)
at android.app.Activity.performCreate(Activity.java:7984)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1309)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3422)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3601)
at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:85)
at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135)
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2066)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:223)
at android.app.ActivityThread.main(ActivityThread.java:7656)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:592)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:947)
My Activity code is -
package com.directsportsnetwork.tv.ui;
import android.annotation.SuppressLint;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.Handler;
import android.view.KeyEvent;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import androidx.core.content.ContextCompat;
import androidx.fragment.app.FragmentActivity;
import com.directsportsnetwork.tv.R;
import com.directsportsnetwork.tv.api.DeviceLogManager;
import com.directsportsnetwork.tv.api.Utils;
import org.json.JSONArray;
import java.util.HashMap;
import uk.co.chrisjenx.calligraphy.CalligraphyContextWrapper;
public class TeamSclActivity extends FragmentActivity {
private String TAG = TeamSclActivity.class.getSimpleName();
private ImageView topShelfImg, topShelfMask;
private TeamSclFragment mTeamSclFragment;
private BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
finish();
}
};
#SuppressWarnings("unchecked")
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_teamscl);
IntentFilter filter = new IntentFilter();
filter.addAction("com.directsportsnetwork.tv.STOP");
registerReceiver(broadcastReceiver, filter);
DeviceLogManager.instance().sendTeamSelectionPageData(TeamSclActivity.this);
topShelfImg = (ImageView) findViewById(R.id.top_shelf_image);
topShelfMask = (ImageView) findViewById(R.id.top_shelf_mask);
Intent intent = getIntent();
if (intent != null) {
try {
String channelData = intent.getStringExtra(Utils.EXTRA_CHANNEL_RESPONSE);
HashMap<String, Integer> teamTrnMap = (HashMap<String, Integer>) intent.getSerializableExtra(Utils.EXTRA_TEAM_TRN_MAP);
mTeamSclFragment = (TeamSclFragment) getFragmentManager().findFragmentById(R.id.main_browse_fragment);
mTeamSclFragment.onResponseData(new JSONArray(channelData), teamTrnMap);
} catch (Exception e) {
e.printStackTrace();
}
setTopShelfMask();
final Handler mHandler = new Handler();
mHandler.postDelayed(new Runnable() {
#Override
public void run() {
try {
mHandler.postDelayed(this, 300);
if (mTeamSclFragment.getView() != null && getCurrentFocus() instanceof RelativeLayout) {
mTeamSclFragment.getView().requestFocus();
mHandler.removeCallbacks(this);
mHandler.removeCallbacksAndMessages(null);
}
}catch (Exception e) {
e.printStackTrace();
}
}
}, 300); //Changes START HERE FOR NEW CHANGES - 10/20/2018
}
}
#Override
protected void attachBaseContext(Context newBase) {
super.attachBaseContext(CalligraphyContextWrapper.wrap(newBase));
}
#Override
protected void onResume() {
super.onResume();
}
#Override
protected void onPause() {
super.onPause();
}
#Override
protected void onDestroy() {
super.onDestroy();
unregisterReceiver(broadcastReceiver);
}
#SuppressLint("MissingSuperCall")
#Override
protected void onSaveInstanceState(Bundle outState) {
//No call for super(). Bug on API Level > 11.
}
// remot Button OnClickListener methods
#Override
public boolean onKeyUp(int keyCode, KeyEvent event) {
switch (keyCode) {
case KeyEvent.KEYCODE_DPAD_LEFT:
case KeyEvent.KEYCODE_DPAD_RIGHT:
case KeyEvent.KEYCODE_DPAD_UP:
case KeyEvent.KEYCODE_DPAD_DOWN:
// Remove shadow over topShelfImage at here
if (mTeamSclFragment != null) {
mTeamSclFragment.startBackgroundTimer();
}
default:
return super.onKeyUp(keyCode, event);
}
}
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_DPAD_LEFT || keyCode == KeyEvent.KEYCODE_DPAD_RIGHT
|| keyCode == KeyEvent.KEYCODE_DPAD_DOWN || keyCode == KeyEvent.KEYCODE_DPAD_UP) {
// Add shadow over topShelfImage at here
topShelfImg.setAlpha(0.3f);
}
if (mTeamSclFragment != null) {
mTeamSclFragment.onMyKeyDown(keyCode, event);
}
return false;
}
public ImageView getTopShelfImg() {
return topShelfImg;
}
public void setTopShelfMask() {
if (Utils.SHOW_TOP_SHELF_MASK) {
topShelfMask.setBackground(ContextCompat.getDrawable(TeamSclActivity.this, R.drawable.ic_mask_bottom));
}
}
}
My Fragment code -
package com.directsportsnetwork.tv.ui;
import static androidx.leanback.app.BackgroundManager.getInstance;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Handler;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.content.ContextCompat;
import androidx.leanback.app.BackgroundManager;
import androidx.leanback.app.BrowseFragment;
import androidx.leanback.widget.ArrayObjectAdapter;
import androidx.leanback.widget.FocusHighlight;
import androidx.leanback.widget.HeaderItem;
import androidx.leanback.widget.ListRow;
import androidx.leanback.widget.ListRowPresenter;
import androidx.leanback.widget.OnItemViewClickedListener;
import androidx.leanback.widget.OnItemViewSelectedListener;
import androidx.leanback.widget.Presenter;
import androidx.leanback.widget.Row;
import androidx.leanback.widget.RowPresenter;
import com.bumptech.glide.Glide;
import com.bumptech.glide.request.target.CustomTarget;
import com.bumptech.glide.request.transition.Transition;
import com.directsportsnetwork.tv.R;
import com.directsportsnetwork.tv.api.OnResponseReceived;
import com.directsportsnetwork.tv.api.TvApplication;
import com.directsportsnetwork.tv.api.Utils;
import com.directsportsnetwork.tv.model.Team;
import com.directsportsnetwork.tv.presenter.TeamPresenter;
import com.directsportsnetwork.tv.provider.DataBaseHelper;
import org.json.JSONArray;
import org.json.JSONObject;
import java.net.URI;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Random;
import java.util.Timer;
import java.util.TimerTask;
public class TeamSclFragment extends BrowseFragment implements OnResponseReceived {
private final String TAGS = "TeamSclFragment";
private final Handler mHandler = new Handler();
private Drawable mDefaultBackground;
private DisplayMetrics mMetrics;
private Timer mBackgroundTimer;
private URI mBackgroundURI;
private URI defaultBackgroundURI;
public Team selectedTeam;
private JSONArray teamData;
private HashMap<String, Integer> teamTrnMap;
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
}
private boolean isFavoriteDisable(String teamId) {
return !(teamTrnMap != null && teamTrnMap.get(teamId) != null);
}
private int getTrnByTeamId(String teamId) {
return teamTrnMap.get(teamId);
}
#Override
public void onResponseData(JSONArray data, HashMap<String, Integer> teamTrnMap) {
try {
Log.e(TAGS, "apiResponse: " + data);
teamData = data;
this.teamTrnMap = teamTrnMap;
prepareBackgroundManager();
setupUIElements();
// Set rows as per data fetched form API
loadTeamRows(teamData);
setupEventListeners();
} catch (Exception e) {
e.printStackTrace();
}
}
#Override
public void onDestroy() {
super.onDestroy();
if (null != mBackgroundTimer) {
mBackgroundTimer.cancel();
}
}
#Override
public void onResume() {
super.onResume();
if (TvApplication.isFavChanged && teamData != null) {
loadTeamRows(teamData);
TvApplication.isFavChanged = false;
if (getView() != null) {
getView().requestFocus();
setSelectedPosition(0, true);
startBackgroundTimer();
}
}
}
#Override
public void onPause() {
super.onPause();
}
public void onMyKeyDown(int keyCode, KeyEvent event) {
//do whatever you want here
switch (keyCode) {
case KeyEvent.KEYCODE_BACK:
getActivity().finish();
getActivity().overridePendingTransition(android.R.anim.fade_in, android.R.anim.fade_out);
break;
}
}
private void loadTeamRows(JSONArray teamCategoryList) {
try {
ArrayList<Team> favTeamList = new ArrayList<>();
if (Utils.isStoragePermissionGranted(getActivity())) {
DataBaseHelper dataBase = DataBaseHelper.getInstance(getActivity());
favTeamList = dataBase.getAllFavorites();
} else {
favTeamList.add(null);
Utils.showToast(getActivity(), getResources().getString(R.string.no_storage_permission));
}
ListRowPresenter mListRowPresenter = new ListRowPresenter(FocusHighlight.ZOOM_FACTOR_NONE, true);
ArrayObjectAdapter mRowsAdapter = new ArrayObjectAdapter(mListRowPresenter);
TeamPresenter teamPresenter = new TeamPresenter();
for (int i = 0; i < teamCategoryList.length() + 1; i++) {
ArrayObjectAdapter listRowAdapter = new ArrayObjectAdapter(teamPresenter);
if (i == 0) {
// This is to create Favorite card row
for (int index = 0; index < favTeamList.size(); index++) {
if (favTeamList.get(index) == null) {
listRowAdapter.add(getResources().getString(R.string.favorites));
} else {
Team team = favTeamList.get(index);
team.setIsFavorite(1);
if (isFavoriteDisable(team.getId())) {
// TODO: Team is disabled, remove it from favorites
DataBaseHelper dataBase = DataBaseHelper.getInstance(getActivity());
dataBase.removeFavorite(team.getId());
TvApplication.isFavChanged = true;
continue;
} else {
team.setReleaseNo(getTrnByTeamId(team.getId()));
}
listRowAdapter.add(team);
}
}
HeaderItem header = new HeaderItem(i, "Favorites");
mRowsAdapter.add(new ListRow(header, listRowAdapter));
} else {
JSONArray teamList = teamCategoryList.getJSONObject(i - 1).getJSONArray("team");
String category = teamCategoryList.getJSONObject(i - 1).getString("name");
String categoryId = teamCategoryList.getJSONObject(i - 1).getString("id");
for (int index = 0; index < teamList.length(); index++) {
JSONObject teamObj = teamList.getJSONObject(index);
String id = teamObj.getString("id");
String name = teamObj.getString("name");
String shortdesc = teamObj.getString("shortdesc");
String longdesc = teamObj.getString("longdesc");
int trn = teamObj.getInt("trn");
//trn stands for Team Release Number
Team team = new Team();
team.setCatId(categoryId);
team.setCatName(category);
team.setId(id);
team.setName(name);
team.setShortdesc(shortdesc);
team.setLongdesc(longdesc);
team.setIsFavorite(0);
team.setReleaseNo(trn);
if (category.equalsIgnoreCase("NASCAR")) {
team.setIsNascar(1);
} else {
team.setIsNascar(0);
}
listRowAdapter.add(team);
}
HeaderItem header = new HeaderItem(i, category);
mRowsAdapter.add(new ListRow(header, listRowAdapter));
}
}
setAdapter(mRowsAdapter);
} catch (Exception e) {
e.printStackTrace();
}
}
private void prepareBackgroundManager() {
BackgroundManager mBackgroundManager = getInstance(getActivity());
mBackgroundManager.attach(getActivity().getWindow());
mDefaultBackground = ContextCompat.getDrawable(getActivity(), R.drawable.default_background);
mBackgroundManager.setColor(Color.BLACK);
mMetrics = new DisplayMetrics();
getActivity().getWindowManager().getDefaultDisplay().getMetrics(mMetrics);
}
private void setupUIElements() {
getTitleView().setVisibility(View.GONE);
// To hide left side header for BrowseFragment
setHeadersState(HEADERS_DISABLED);
setHeadersTransitionOnBackEnabled(true);
}
private void setupEventListeners() {
setOnItemViewClickedListener(new ItemViewClickedListener());
setOnItemViewSelectedListener(new ItemViewSelectedListener());
}
protected void updateBackground(String uri) {
try {
int width = mMetrics.widthPixels;
int height = mMetrics.heightPixels;
final TeamSclActivity activity = ((TeamSclActivity) getActivity());
if (activity.getTopShelfImg().getDrawable().getConstantState() == getResources().getDrawable(R.drawable.ic_start).getConstantState() && (uri == defaultBackgroundURI.toString())) {
} else {
//start
if (activity != null) {
Glide.with(activity).load(uri).error(mDefaultBackground).placeholder(R.drawable.teamblank).into(new CustomTarget<Drawable>(width, height) {
#Override
public void onResourceReady(#NonNull Drawable resource, #Nullable Transition<? super Drawable> transition) {
activity.getTopShelfImg().setImageDrawable(resource);
Utils.crossfade(activity.getTopShelfImg());
}
#Override
public void onLoadCleared(#Nullable Drawable placeholder) {
}
});
}
//end
}
mBackgroundTimer.cancel();
} catch (Exception e) {
e.printStackTrace();
}
}
public void startBackgroundTimer() {
if (mBackgroundTimer != null) {
mBackgroundTimer.cancel();
}
mBackgroundTimer = new Timer();
mBackgroundTimer.schedule(new UpdateBackgroundTask(), Utils.BACKGROUND_UPDATE_DELAY);
}
private final class ItemViewClickedListener implements OnItemViewClickedListener {
#Override
public void onItemClicked(Presenter.ViewHolder itemViewHolder, Object item, RowPresenter.ViewHolder rowViewHolder, Row row) {
if (item instanceof Team) {
Team team = (Team) item;
Intent intent = new Intent(getActivity(), TeamChnlActivity.class);
intent.putExtra(Utils.EXTRA_TEAM, team);
startActivity(intent);
} else if (item instanceof String) {
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setMessage(getResources().getString(R.string.favorite_alert_msg));
builder.setCancelable(true);
builder.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
AlertDialog alert = builder.create();
alert.show();
}
}
}
private final class ItemViewSelectedListener implements OnItemViewSelectedListener {
#Override
public void onItemSelected(Presenter.ViewHolder itemViewHolder, Object item, RowPresenter.ViewHolder rowViewHolder, Row row) {
if (item instanceof Team) {
Team team = ((Team) item);
try {
selectedTeam = team;
mBackgroundURI = new URI(team.getTopShelfImageUrl(team.getId(), team.getReleaseNo()));
defaultBackgroundURI = new URI(Utils.MEDIA_PREFIX_URL + "/tv/images/app/start.jpg?");
if (team.getIsFavorite() == 1) {
startBackgroundTimer();
}
} catch (Exception e) {
e.printStackTrace();
}
} else if (item instanceof String) {
try {
selectedTeam = null;
Random random = new Random();
mBackgroundURI = new URI(Utils.MEDIA_PREFIX_URL + "/tv/images/app/start.jpg?" + random.nextInt(100));
defaultBackgroundURI = mBackgroundURI;
startBackgroundTimer();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
private class UpdateBackgroundTask extends TimerTask {
#Override
public void run() {
mHandler.post(new Runnable() {
#Override
public void run() {
if (mBackgroundURI != null) {
updateBackground(mBackgroundURI.toString());
}
}
});
}
}
}
My activity_teamscl.xml code -
<?xml version="1.0" encoding="utf-8"?>
<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">
<fragment
android:id="#+id/main_browse_fragment"
android:name="com.directsportsnetwork.tv.ui.TeamSclFragment"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_alignParentBottom="true"
android:layout_alignTop="#+id/center_baseline"
tools:context=".ui.TeamSclActivity"
tools:deviceIds="tv"
tools:ignore="MergeRootFrame" />
</RelativeLayout>
Hello everyone i was trying to make Custom list of view with volley feed following this tutorial: http://www.androidhive.info/2014/06/android-facebook-like-custom-listview-feed-using-volley/
but i got an error with the image loader i can't get the hang of it , i hope if someone can tell me what is the problem and how should i solve it in the first place :)
thanks in advance
this is the error:
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.asro9.customfeed/com.example.asro9.customfeed.MainActivity}: java.lang.NullPointerException
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2184)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2233)
at android.app.ActivityThread.access$800(ActivityThread.java:135)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1196)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5001)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:785)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:601)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.NullPointerException
at Adapter.FeedListAdapter.<init>(FeedListAdapter.java:33)
at com.example.asro9.customfeed.MainActivity.onCreate(MainActivity.java:50)
at android.app.Activity.performCreate(Activity.java:5231)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2148)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2233)
at android.app.ActivityThread.access$800(ActivityThread.java:135)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1196)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5001)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:785)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:601)
at dalvik.system.NativeStart.main(Native Method)
i will show up the classes i have created !
FeedListAdapter.java
package Adapter;
import java.util.List;
import android.app.Activity;
import android.content.Context;
import android.text.Html;
import android.text.TextUtils;
import android.text.format.DateUtils;
import android.text.method.LinkMovementMethod;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;
import com.android.volley.toolbox.ImageLoader;
import com.android.volley.toolbox.NetworkImageView;
import com.example.asro9.customfeed.FeedImageView;
import com.example.asro9.customfeed.R;
import CustomFeed.AppController;
import Data.FeedItem;
/**
* Created by asro9 on 3/7/2016.
*/
public class FeedListAdapter extends BaseAdapter {
private Activity activity;
private LayoutInflater inflater;
private List<FeedItem> feedItems;
ImageLoader imageLoader = AppController.getInstance().getImageLoader();
public FeedListAdapter(Activity activity, List<FeedItem> feedItems) {
this.activity = activity;
this.feedItems = feedItems;
}
#Override
public int getCount() {
return feedItems.size();
}
#Override
public Object getItem(int location) {
return feedItems.get(location);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if (inflater == null)
inflater = (LayoutInflater) activity
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if (convertView == null)
convertView = inflater.inflate(R.layout.feed_item, null);
if (imageLoader == null)
imageLoader = AppController.getInstance().getImageLoader();
TextView name = (TextView) convertView.findViewById(R.id.name);
TextView timestamp = (TextView) convertView
.findViewById(R.id.timestamp);
TextView statusMsg = (TextView) convertView
.findViewById(R.id.txtStatusMsg);
TextView url = (TextView) convertView.findViewById(R.id.txtUrl);
NetworkImageView profilePic = (NetworkImageView) convertView
.findViewById(R.id.profilePic);
FeedImageView feedImageView = (FeedImageView) convertView
.findViewById(R.id.feedImage1);
FeedItem item = feedItems.get(position);
name.setText(item.getName());
// Converting timestamp into x ago format
CharSequence timeAgo = DateUtils.getRelativeTimeSpanString(
Long.parseLong(item.getTimeStamp()),
System.currentTimeMillis(), DateUtils.SECOND_IN_MILLIS);
timestamp.setText(timeAgo);
// Chcek for empty status message
if (!TextUtils.isEmpty(item.getStatus())) {
statusMsg.setText(item.getStatus());
statusMsg.setVisibility(View.VISIBLE);
} else {
// status is empty, remove from view
statusMsg.setVisibility(View.GONE);
}
// Checking for null feed url
if (item.getUrl() != null) {
url.setText(Html.fromHtml("<a href=\"" + item.getUrl() + "\">"
+ item.getUrl() + "</a> "));
// Making url clickable
url.setMovementMethod(LinkMovementMethod.getInstance());
url.setVisibility(View.VISIBLE);
} else {
// url is null, remove from the view
url.setVisibility(View.GONE);
}
// user profile pic
profilePic.setImageUrl(item.getProfilePic(), imageLoader);
// Feed image
if (item.getImge() != null) {
feedImageView.setImageUrl(item.getImge(), imageLoader);
feedImageView.setVisibility(View.VISIBLE);
feedImageView
.setResponseObserver(new FeedImageView.ResponseObserver() {
#Override
public void onError() {
}
#Override
public void onSuccess() {
}
});
} else {
feedImageView.setVisibility(View.GONE);
}
return convertView;
}
}
FeedImageVie.java
package com.example.asro9.customfeed;
import android.content.Context;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.LinearLayout.LayoutParams;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.ImageLoader;
import com.android.volley.toolbox.ImageLoader.ImageContainer;
import com.android.volley.toolbox.ImageLoader.ImageListener;
/**
* Created by asro9 on 3/7/2016.
*/
public class FeedImageView extends ImageView {
public interface ResponseObserver {
public void onError();
public void onSuccess();
}
private ResponseObserver mObserver;
public void setResponseObserver(ResponseObserver observer) {
mObserver = observer;
}
/**
* The URL of the network image to load
*/
private String mUrl;
/**
* Resource ID of the image to be used as a placeholder until the network
* image is loaded.
*/
private int mDefaultImageId;
/**
* Resource ID of the image to be used if the network response fails.
*/
private int mErrorImageId;
/**
* Local copy of the ImageLoader.
*/
private ImageLoader mImageLoader;
/**
* Current ImageContainer. (either in-flight or finished)
*/
private ImageContainer mImageContainer;
public FeedImageView(Context context) {
this(context, null);
}
public FeedImageView(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
public FeedImageView(Context context, AttributeSet attrs,
int defStyle) {
super(context, attrs, defStyle);
}
/**
* Sets URL of the image that should be loaded into this view. Note that
* calling this will immediately either set the cached image (if available)
* or the default image specified by
* {#link VolleyImageView#setDefaultImageResId(int)} on the view.
*
* NOTE: If applicable, {#link VolleyImageView#setDefaultImageResId(int)}
* and {#link VolleyImageView#setErrorImageResId(int)} should be called
* prior to calling this function.
*
* #param url
* The URL that should be loaded into this ImageView.
* #param imageLoader
* ImageLoader that will be used to make the request.
*/
public void setImageUrl(String url, ImageLoader imageLoader) {
mUrl = url;
mImageLoader = imageLoader;
// The URL has potentially changed. See if we need to load it.
loadImageIfNecessary(false);
}
/**
* Sets the default image resource ID to be used for this view until the
* attempt to load it completes.
*/
public void setDefaultImageResId(int defaultImage) {
mDefaultImageId = defaultImage;
}
/**
* Sets the error image resource ID to be used for this view in the event
* that the image requested fails to load.
*/
public void setErrorImageResId(int errorImage) {
mErrorImageId = errorImage;
}
/**
* Loads the image for the view if it isn't already loaded.
*
* #param isInLayoutPass
* True if this was invoked from a layout pass, false otherwise.
*/
private void loadImageIfNecessary(final boolean isInLayoutPass) {
final int width = getWidth();
int height = getHeight();
boolean isFullyWrapContent = getLayoutParams() != null
&& getLayoutParams().height == LayoutParams.WRAP_CONTENT
&& getLayoutParams().width == LayoutParams.WRAP_CONTENT;
// if the view's bounds aren't known yet, and this is not a
// wrap-content/wrap-content
// view, hold off on loading the image.
if (width == 0 && height == 0 && !isFullyWrapContent) {
return;
}
// if the URL to be loaded in this view is empty, cancel any old
// requests and clear the
// currently loaded image.
if (TextUtils.isEmpty(mUrl)) {
if (mImageContainer != null) {
mImageContainer.cancelRequest();
mImageContainer = null;
}
setDefaultImageOrNull();
return;
}
// if there was an old request in this view, check if it needs to be
// canceled.
if (mImageContainer != null && mImageContainer.getRequestUrl() != null) {
if (mImageContainer.getRequestUrl().equals(mUrl)) {
// if the request is from the same URL, return.
return;
} else {
// if there is a pre-existing request, cancel it if it's
// fetching a different URL.
mImageContainer.cancelRequest();
setDefaultImageOrNull();
}
}
// The pre-existing content of this view didn't match the current URL.
// Load the new image
// from the network.
ImageContainer newContainer = mImageLoader.get(mUrl,
new ImageListener() {
#Override
public void onErrorResponse(VolleyError error) {
if (mErrorImageId != 0) {
setImageResource(mErrorImageId);
}
if (mObserver != null) {
mObserver.onError();
}
}
#Override
public void onResponse(final ImageContainer response,
boolean isImmediate) {
// If this was an immediate response that was delivered
// inside of a layout
// pass do not set the image immediately as it will
// trigger a requestLayout
// inside of a layout. Instead, defer setting the image
// by posting back to
// the main thread.
if (isImmediate && isInLayoutPass) {
post(new Runnable() {
#Override
public void run() {
onResponse(response, false);
}
});
return;
}
int bWidth = 0, bHeight = 0;
if (response.getBitmap() != null) {
setImageBitmap(response.getBitmap());
bWidth = response.getBitmap().getWidth();
bHeight = response.getBitmap().getHeight();
adjustImageAspect(bWidth, bHeight);
} else if (mDefaultImageId != 0) {
setImageResource(mDefaultImageId);
}
if (mObserver != null) {
mObserver.onSuccess();
}
}
});
// update the ImageContainer to be the new bitmap container.
mImageContainer = newContainer;
}
private void setDefaultImageOrNull() {
if (mDefaultImageId != 0) {
setImageResource(mDefaultImageId);
} else {
setImageBitmap(null);
}
}
#Override
protected void onLayout(boolean changed, int left, int top, int right,
int bottom) {
super.onLayout(changed, left, top, right, bottom);
loadImageIfNecessary(true);
}
#Override
protected void onDetachedFromWindow() {
if (mImageContainer != null) {
// If the view was bound to an image request, cancel it and clear
// out the image from the view.
mImageContainer.cancelRequest();
setImageBitmap(null);
// also clear out the container so we can reload the image if
// necessary.
mImageContainer = null;
}
super.onDetachedFromWindow();
}
#Override
protected void drawableStateChanged() {
super.drawableStateChanged();
invalidate();
}
/*
* Adjusting imageview height
* */
private void adjustImageAspect(int bWidth, int bHeight) {
LinearLayout.LayoutParams params = (LayoutParams) getLayoutParams();
if (bWidth == 0 || bHeight == 0)
return;
int swidth = getWidth();
int new_height = 0;
new_height = swidth * bHeight / bWidth;
params.width = swidth;
params.height = new_height;
setLayoutParams(params);
}
}
the MainActivity.java
package com.example.asro9.customfeed;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.view.Menu;
import android.widget.ListView;
import org.json.JSONException;
import java.util.ArrayList;
import java.util.List;
import Adapter.FeedListAdapter;
import CustomFeed.AppController;
import Data.FeedItem;
import com.android.volley.Cache;
import com.android.volley.Cache.Entry;
import com.android.volley.Request.Method;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.VolleyLog;
import com.android.volley.toolbox.JsonObjectRequest;
import java.io.UnsupportedEncodingException;
import org.json.JSONArray;
import org.json.JSONObject;
public class MainActivity extends Activity {
private static final String TAG = MainActivity.class.getSimpleName();
private ListView listView;
private FeedListAdapter listAdapter;
private List<FeedItem> feedItems;
private String URL_FEED = "http://api.androidhive.info/feed/feed.json";
#SuppressLint("NewApi")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listView = (ListView) findViewById(R.id.list);
feedItems = new ArrayList<FeedItem>();
listAdapter = new FeedListAdapter(this, feedItems);
listView.setAdapter(listAdapter);
// These two lines not needed,
// just to get the look of facebook (changing background color & hiding the icon)
getActionBar().setBackgroundDrawable(new ColorDrawable(Color.parseColor("#3b5998")));
getActionBar().setIcon(
new ColorDrawable(getResources().getColor(android.R.color.transparent)));
// We first check for cached request
Cache cache = AppController.getInstance().getRequestQueue().getCache();
Entry entry = cache.get(URL_FEED);
if (entry != null) {
// fetch the data from cache
try {
String data = new String(entry.data, "UTF-8");
try {
parseJsonFeed(new JSONObject(data));
} catch (JSONException e) {
e.printStackTrace();
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
} else {
// making fresh volley request and getting json
JsonObjectRequest jsonReq = new JsonObjectRequest(Method.GET,
URL_FEED, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
VolleyLog.d(TAG, "Response: " + response.toString());
if (response != null) {
parseJsonFeed(response);
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
}
});
// Adding request to volley request queue
AppController.getInstance().addToRequestQueue(jsonReq);
}
}
/**
* Parsing json reponse and passing the data to feed view list adapter
* */
private void parseJsonFeed(JSONObject response) {
try {
JSONArray feedArray = response.getJSONArray("feed");
for (int i = 0; i < feedArray.length(); i++) {
JSONObject feedObj = (JSONObject) feedArray.get(i);
FeedItem item = new FeedItem();
item.setId(feedObj.getInt("id"));
item.setName(feedObj.getString("name"));
// Image might be null sometimes
String image = feedObj.isNull("image") ? null : feedObj
.getString("image");
item.setImge(image);
item.setStatus(feedObj.getString("status"));
item.setProfilePic(feedObj.getString("profilePic"));
item.setTimeStamp(feedObj.getString("timeStamp"));
// url might be null sometimes
String feedUrl = feedObj.isNull("url") ? null : feedObj
.getString("url");
item.setUrl(feedUrl);
feedItems.add(item);
}
// notify data changes to list adapater
listAdapter.notifyDataSetChanged();
} catch (JSONException e) {
e.printStackTrace();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
}
AppController.java
package CustomFeed;
import android.app.Application;
import android.text.TextUtils;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.toolbox.ImageLoader;
import com.android.volley.toolbox.Volley;
import Volly.LruBitmapCache;
/**
* Created by asro9 on 3/9/2016.
*/
public class AppController extends Application {
public static final String TAG = AppController.class.getSimpleName();
private RequestQueue mRequestQueue;
private ImageLoader mImageLoader;
LruBitmapCache mLruBitmapCache;
private static AppController mInstance;
#Override
public void onCreate() {
super.onCreate();
mInstance = this;
}
public static synchronized AppController getInstance() {
return mInstance;
}
public RequestQueue getRequestQueue() {
if (mRequestQueue == null) {
mRequestQueue = Volley.newRequestQueue(getApplicationContext());
}
return mRequestQueue;
}
public ImageLoader getImageLoader() {
getRequestQueue();
if (mImageLoader == null) {
getLruBitmapCache();
mImageLoader = new ImageLoader(this.mRequestQueue, mLruBitmapCache);
}
return this.mImageLoader;
}
public LruBitmapCache getLruBitmapCache() {
if (mLruBitmapCache == null)
mLruBitmapCache = new LruBitmapCache();
return this.mLruBitmapCache;
}
public <T> void addToRequestQueue(Request<T> req, String tag) {
req.setTag(TextUtils.isEmpty(tag) ? TAG : tag);
getRequestQueue().add(req);
}
public <T> void addToRequestQueue(Request<T> req) {
req.setTag(TAG);
getRequestQueue().add(req);
}
public void cancelPendingRequests(Object tag) {
if (mRequestQueue != null) {
mRequestQueue.cancelAll(tag);
}
}
}
feeditem.java
package Data;
/**
* Created by asro9 on 3/7/2016.
*/
public class FeedItem {
private int id;
private String name, status, image, profilePic, timeStamp, url;
public FeedItem() {
}
public FeedItem(int id, String name, String image, String status,
String profilePic, String timeStamp, String url) {
super();
this.id = id;
this.name = name;
this.image = image;
this.status = status;
this.profilePic = profilePic;
this.timeStamp = timeStamp;
this.url = url;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getImge() {
return image;
}
public void setImge(String image) {
this.image = image;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public String getProfilePic() {
return profilePic;
}
public void setProfilePic(String profilePic) {
this.profilePic = profilePic;
}
public String getTimeStamp() {
return timeStamp;
}
public void setTimeStamp(String timeStamp) {
this.timeStamp = timeStamp;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
}
volley cache
LruBitmapCache :
package Volly;
import android.graphics.Bitmap;
import android.support.v4.util.LruCache;
import com.android.volley.toolbox.ImageLoader.ImageCache;
/**
* Created by asro9 on 3/7/2016.
*/
public class LruBitmapCache extends LruCache<String, Bitmap> implements
ImageCache {
public static int getDefaultLruCacheSize() {
final int maxMemory = (int) (Runtime.getRuntime().maxMemory() / 1024);
final int cacheSize = maxMemory / 8;
return cacheSize;
}
public LruBitmapCache() {
this(getDefaultLruCacheSize());
}
public LruBitmapCache(int sizeInKiloBytes) {
super(sizeInKiloBytes);
}
#Override
protected int sizeOf(String key, Bitmap value) {
return value.getRowBytes() * value.getHeight() / 1024;
}
#Override
public Bitmap getBitmap(String url) {
return get(url);
}
#Override
public void putBitmap(String url, Bitmap bitmap) {
put(url, bitmap);
}
}
The error is self explanatory, the crash is here:
ImageLoader imageLoader = AppController.getInstance().getImageLoader();
getInstance is returning null.
I'm a new programmer,recently i have a bug but can't solve
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.android.Bl
uetoothChat/com.example.android.BluetoothFileTran.FileTranActivity}:
java.lang.NullPointerException
logcat stack trace
04-26 10:19:43.613: E/BluetoothChat(21754): +++ ON CREATE +++
04-26 10:19:44.213: E/CheckPermission(21754): _bluetooth code = 1
04-26 10:19:44.213: E/BluetoothChat(21754): ++ ON START ++
04-26 10:19:44.233: E/BluetoothChat(21754): + ON RESUME +
04-26 10:19:44.233: E/CheckPermission(21754): _bluetooth code = 13
04-26 10:19:45.643: E/BluetoothChat(21754): - ON PAUSE -
04-26 10:19:47.223: E/BluetoothChat(21754): + ON RESUME +
04-26 10:19:55.093: E/BluetoothChat(21754): - ON PAUSE -
04-26 10:20:21.363: E/AndroidRuntime(21754): FATAL EXCEPTION: main
04-26 10:20:21.363: E/AndroidRuntime(21754): Process: com.example.android.BluetoothChat, PID: 21754
04-26 10:20:21.363: E/AndroidRuntime(21754): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.android.BluetoothChat/com.example.android.BluetoothFileTran.FileTranActivity}: java.lang.NullPointerException
04-26 10:20:21.363: E/AndroidRuntime(21754): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2190)
04-26 10:20:21.363: E/AndroidRuntime(21754): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2250)
04-26 10:20:21.363: E/AndroidRuntime(21754): at android.app.ActivityThread.access$800(ActivityThread.java:139)
04-26 10:20:21.363: E/AndroidRuntime(21754): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1200)
04-26 10:20:21.363: E/AndroidRuntime(21754): at android.os.Handler.dispatchMessage(Handler.java:102)
04-26 10:20:21.363: E/AndroidRuntime(21754): at android.os.Looper.loop(Looper.java:136)
04-26 10:20:21.363: E/AndroidRuntime(21754): at android.app.ActivityThread.main(ActivityThread.java:5049)
04-26 10:20:21.363: E/AndroidRuntime(21754): at java.lang.reflect.Method.invokeNative(Native Method)
04-26 10:20:21.363: E/AndroidRuntime(21754): at java.lang.reflect.Method.invoke(Method.java:515)
04-26 10:20:21.363: E/AndroidRuntime(21754): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:818)
04-26 10:20:21.363: E/AndroidRuntime(21754): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:634)
04-26 10:20:21.363: E/AndroidRuntime(21754): at de.robv.android.xposed.XposedBridge.main(XposedBridge.java:132)
04-26 10:20:21.363: E/AndroidRuntime(21754): at dalvik.system.NativeStart.main(Native Method)
04-26 10:20:21.363: E/AndroidRuntime(21754): Caused by: java.lang.NullPointerException
04-26 10:20:21.363: E/AndroidRuntime(21754): at com.example.android.BluetoothFileTran.FileTranActivity.onCreate(FileTranActivity.java:66)
04-26 10:20:21.363: E/AndroidRuntime(21754): at android.app.Activity.performCreate(Activity.java:5293)
04-26 10:20:21.363: E/AndroidRuntime(21754): at de.robv.android.xposed.XposedBridge.invokeOriginalMethodNative(Native Method)
04-26 10:20:21.363: E/AndroidRuntime(21754): at de.robv.android.xposed.XposedBridge.handleHookedMethod(XposedBridge.java:631)
04-26 10:20:21.363: E/AndroidRuntime(21754): at android.app.Activity.performCreate(Native Method)
04-26 10:20:21.363: E/AndroidRuntime(21754): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
04-26 10:20:21.363: E/AndroidRuntime(21754): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2154)
04-26 10:20:21.363: E/AndroidRuntime(21754): ... 12 more
here is Bluetoooth.java
package com.example.android.BluetoothChat;
import com.example.android.BluetoothChat.R;
import com.example.android.BluetoothChat.service.BluetoothChatService;
import com.example.android.BluetoothFileTran.FileTranActivity;
import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.ContentValues;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.Message;
import android.util.Log;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.inputmethod.EditorInfo;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
public class BluetoothChat extends Activity {
public static final String SEND_FILE_NAME = "sendFileName";
public static final int REQUEST_FILE = 1000;
private static String mSendFileName ;
private Handler mOthHandler;
private static String mAddress ;
private static final String TAG = "BluetoothChat";
private static final boolean D = true;
public static final int MESSAGE_STATE_CHANGE = 1;
public static final int MESSAGE_READ = 2;
public static final int MESSAGE_WRITE = 3;
public static final int MESSAGE_DEVICE_NAME = 4;
public static final int MESSAGE_TOAST = 5;
public static final String DEVICE_NAME = "device_name";
public static final String TOAST = "toast";
private static final int REQUEST_CONNECT_DEVICE = 1;
private static final int REQUEST_ENABLE_BT = 2;
private ListView mConversationView;
private EditText mOutEditText;
private Button mSendButton;
private String mConnectedDeviceName = null;
private ArrayAdapter<String> mConversationArrayAdapter;
private StringBuffer mOutStringBuffer;
private BluetoothAdapter mBluetoothAdapter = null;
private BluetoothChatService mChatService = null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if(D) Log.e(TAG, "+++ ON CREATE +++");
setContentView(R.layout.main);
mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
if (mBluetoothAdapter == null) {
Toast.makeText(this, "Bluetooth is not available", Toast.LENGTH_LONG).show();
finish();
return;
}
}
#Override
public void onStart() {
super.onStart();
if(D) Log.e(TAG, "++ ON START ++");
if (!mBluetoothAdapter.isEnabled()) {
Intent enableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableIntent, REQUEST_ENABLE_BT);
} else {
if (mChatService == null) setupChat();
}
}
private void setupChat() {
Log.d(TAG, "setupChat()");
mConversationArrayAdapter = new ArrayAdapter<String>(this, R.layout.message);
mConversationView = (ListView) findViewById(R.id.in);
mConversationView.setAdapter(mConversationArrayAdapter);
mOutEditText = (EditText) findViewById(R.id.edit_text_out);
mOutEditText.setOnEditorActionListener(mWriteListener);
mSendButton = (Button) findViewById(R.id.button_send);
mSendButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
TextView view = (TextView) findViewById(R.id.edit_text_out);
String message = view.getText().toString();
sendMessage(message);
}
});
mChatService = new BluetoothChatService(this, mHandler);
mOutStringBuffer = new StringBuffer("");
}
#Override
public synchronized void onResume() {
super.onResume();
if(D) Log.e(TAG, "+ ON RESUME +");
if (mChatService != null) {
if (mChatService.getState() == BluetoothChatService.STATE_NONE) {
mChatService.start();
}
}
}
private TextView.OnEditorActionListener mWriteListener =
new TextView.OnEditorActionListener() {
public boolean onEditorAction(TextView view, int actionId, KeyEvent event) {
//EditorInfo.IME_NULL KeyEvent.ACTION_UP
if (actionId == EditorInfo.IME_NULL && event.getAction() == KeyEvent.ACTION_UP) {
String message = view.getText().toString();
sendMessage(message);
}
if(D) Log.i(TAG, "END onEditorAction");
return true;
}
};
#Override
public synchronized void onPause() {
super.onPause();
if(D) Log.e(TAG, "- ON PAUSE -");
}
#Override
public void onStop() {
super.onStop();
if(D) Log.e(TAG, "-- ON STOP --");
}
#Override
public void onDestroy() {
super.onDestroy();
if (mChatService != null) mChatService.stop();
if(D) Log.e(TAG, "--- ON DESTROY ---");
}
private void sendMessage(String message) {
if (mChatService.getState() != BluetoothChatService.STATE_CONNECTED) {
Toast.makeText(this, R.string.not_connected, Toast.LENGTH_SHORT).show();
return;
}
if (message.length() > 0) {
byte[] send = message.getBytes();
mChatService.write(send);
mOutStringBuffer.setLength(0);
mOutEditText.setText(mOutStringBuffer);
}
}
private final Handler mHandler = new Handler() {
#Override
public void handleMessage(Message msg) {
switch (msg.what) {
case MESSAGE_STATE_CHANGE:
if(D) Log.i(TAG, "MESSAGE_STATE_CHANGE: " + msg.arg1);
switch (msg.arg1) {
case BluetoothChatService.STATE_CONNECTED:
mConversationArrayAdapter.clear();
break;
case BluetoothChatService.STATE_CONNECTING:
break;
case BluetoothChatService.STATE_LISTEN:
case BluetoothChatService.STATE_NONE:
break;
}
break;
case MESSAGE_WRITE:
byte[] writeBuf = (byte[]) msg.obj;
String writeMessage = new String(writeBuf);
mConversationArrayAdapter.add("Me: " + writeMessage);
break;
case MESSAGE_READ:
byte[] readBuf = (byte[]) msg.obj;
String readMessage = new String(readBuf, 0, msg.arg1);
mConversationArrayAdapter.add(mConnectedDeviceName+": " + readMessage);
break;
case MESSAGE_DEVICE_NAME:
mConnectedDeviceName = msg.getData().getString(DEVICE_NAME);
// mAddress = msg.getData().getString(DEVICE_ADDRESS);
Toast.makeText(getApplicationContext(), "Connected to "
+ mConnectedDeviceName, Toast.LENGTH_SHORT).show();
break;
case MESSAGE_TOAST:
Toast.makeText(getApplicationContext(), msg.getData().getString(TOAST),
Toast.LENGTH_SHORT).show();
break;
}
}
};
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if(D) Log.d(TAG, "onActivityResult " + resultCode);
switch (requestCode) {
case REQUEST_CONNECT_DEVICE:
if (resultCode == Activity.RESULT_OK) {
mAddress = data.getExtras()
.getString(DeviceListActivity.EXTRA_DEVICE_ADDRESS);
BluetoothDevice device = mBluetoothAdapter.getRemoteDevice(mAddress);
mChatService.connect(device);
}
break;
case REQUEST_ENABLE_BT:
if (resultCode == Activity.RESULT_OK) {
setupChat();
} else {
Log.d(TAG, "BT not enabled");
Toast.makeText(this, R.string.bt_not_enabled_leaving, Toast.LENGTH_SHORT).show();
finish();
}
break;
case REQUEST_FILE:
if (resultCode == Activity.RESULT_OK) {
mSendFileName = data.getExtras().getString(SEND_FILE_NAME);
doSendFileByBluetooth();
}
break;
}
}
private void doSendFileByBluetooth() {
String filePath = mSendFileName.trim();
if(!filePath.equals("null")){
if(null == mOthHandler){
HandlerThread handlerThread = new HandlerThread("other_thread");
handlerThread.start();
mOthHandler = new Handler(handlerThread.getLooper());
}
mOthHandler.post(new Runnable() {
#Override
public void run() {
ContentValues cv = new ContentValues();
String uri = "file://" + mSendFileName.trim();
cv.put("uri", uri);
cv.put("destination", mAddress.trim());
cv.put("direction", 0);
Long ts = System.currentTimeMillis();
cv.put("timestamp", ts);
getContentResolver().insert(Uri.parse("content://com.android.bluetooth.opp/btopp"), cv);
}
});
}else {
Toast.makeText(BluetoothChat.this, "请选择要发送的文件!", Toast.LENGTH_LONG).show();
}
}
private void ensureDiscoverable() {
if(D) Log.d(TAG, "ensure discoverable");
if (mBluetoothAdapter.getScanMode() !=
BluetoothAdapter.SCAN_MODE_CONNECTABLE_DISCOVERABLE) {
Intent discoverableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
discoverableIntent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 300);
startActivity(discoverableIntent);
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.option_menu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.scan:
Intent serverIntent = new Intent(this, DeviceListActivity.class);
startActivityForResult(serverIntent, REQUEST_CONNECT_DEVICE);
return true;
case R.id.discoverable:
ensureDiscoverable();
return true;
case R.id.file_transport:
Intent fileIntent = new Intent(this, FileTranActivity.class);
startActivityForResult(fileIntent, REQUEST_FILE);
return true;
}
return false;
}
}
here is FileTranActivity.java
package com.example.android.BluetoothFileTran;
import java.io.File;
import com.example.android.BluetoothChat.BluetoothChat;
import com.example.android.BluetoothChat.R;
import com.example.android.BluetoothFileTran.adapter.AdapterManager;
import com.example.android.BluetoothFileTran.adapter.FileListAdapter;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.HandlerThread;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;
public class FileTranActivity extends Activity {
ListView mFileListView;
FileListAdapter mFileListAdapter;
AdapterManager mAdapterManager;
private Handler mOtherHandler;
private Runnable updateFileListRunnable;
private File file;
private String sdcardPath;
private String path;
Button mBackBtn;
Button mEnsureBtn;
Button mCancelBtn;
TextView mLastClickView;
TextView mNowClickView;
private boolean isSelected = false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.file_list);
setResult(Activity.RESULT_CANCELED);
mFileListView = (ListView) findViewById(R.id.fileListView);
mBackBtn = (Button) findViewById(R.id.selectFileBackBtn);
mEnsureBtn = (Button) findViewById(R.id.selectFileEnsureBtn);
mCancelBtn = (Button) findViewById(R.id.selectFileCancelBtn);
sdcardPath = Environment.getExternalStorageDirectory().getAbsolutePath();
path = sdcardPath;
mAdapterManager = BluetoothApplication.getInstance().getAdapterManager();
mFileListView.setAdapter(mAdapterManager.getFileListAdapter());
mAdapterManager.updateFileListAdapter(path);
mFileListView.setOnItemClickListener(mFileListOnItemClickListener);
mBackBtn.setOnClickListener(mBackBtnClickListener);
mEnsureBtn.setOnClickListener(mEnsureBtnClickListener);
mCancelBtn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
FileTranActivity.this.finish();
}
});
}
private OnItemClickListener mFileListOnItemClickListener = new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
file = (File) mFileListView.getAdapter().getItem(position);
if(file.isFile()){
if(null != mLastClickView){
mLastClickView.setTextColor(Color.WHITE);
}
mNowClickView = (TextView) view.findViewById(R.id.fileNameTV);
mNowClickView.setTextColor(Color.BLUE);
isSelected = true;
mLastClickView = mNowClickView;
}else {
path = file.getAbsolutePath();
updateFileList();
}
}
};
private OnClickListener mBackBtnClickListener = new OnClickListener() {
#Override
public void onClick(View v) {
if(path.equals(sdcardPath)){
return ;
}
path = path.substring(0, path.lastIndexOf("/"));
updateFileList();
}
};
private OnClickListener mEnsureBtnClickListener = new OnClickListener() {
#Override
public void onClick(View v) {
if(!isSelected){
Toast.makeText(FileTranActivity.this, "请选择文件!", Toast.LENGTH_LONG).show();
return ;
}
Intent intent = new Intent();
intent.putExtra(BluetoothChat.SEND_FILE_NAME, file.getAbsolutePath());
setResult(Activity.RESULT_OK, intent);
FileTranActivity.this.finish();
}
};
private void updateFileList() {
if(null != mLastClickView){
mLastClickView.setTextColor(Color.WHITE);
mLastClickView = null;
isSelected = false;
}
if(null == updateFileListRunnable){
updateFileListRunnable = new Runnable() {
#Override
public void run() {
mAdapterManager.updateFileListAdapter(path);
}
};
}
if(null == mOtherHandler){
HandlerThread handlerThread = new HandlerThread("other_thread");
handlerThread.start();
mOtherHandler = new Handler(handlerThread.getLooper());
}
mOtherHandler.post(updateFileListRunnable);
}
}
then ,I find it point out the error in the FileTranActivity.java
mAdapterManager = BluetoothApplication.getInstance().getAdapterManager();
so ,here is BluetoothApplication.java
package com.example.android.BluetoothFileTran;
import com.example.android.BluetoothFileTran.adapter.AdapterManager;
import com.example.android.BluetoothFileTran.adapter.util.TouchObject;
import android.app.Application;
public class BluetoothApplication extends Application {
private static BluetoothApplication application;
private AdapterManager mAdapterManager;
private TouchObject mTouchObject;
#Override
public void onCreate() {
super.onCreate();
if(null == application){
application = this;
}
mTouchObject = new TouchObject();
}
public static BluetoothApplication getInstance(){
return application;
}
public AdapterManager getAdapterManager() {
return mAdapterManager;
}
public void setAdapterManager(AdapterManager adapterManager) {
this.mAdapterManager = adapterManager;
}
public TouchObject getTouchObject() {
return mTouchObject;
}
public void setTouchObject(TouchObject touchObject) {
this.mTouchObject = touchObject;
}
}
and AdapterManager.java
package com.example.android.BluetoothFileTran.adapter;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import android.bluetooth.BluetoothDevice;
import android.content.Context;
import android.os.Handler;
import com.example.android.BluetoothChat.R;
import com.example.android.BluetoothFileTran.adapter.FileListAdapter;
public class AdapterManager {
private Context mContext;
private FileListAdapter mFileListAdapter;
private List<BluetoothDevice> mDeviceList;
private List<File> mFileList;
private Handler mainHandler;
public AdapterManager(Context context){
this.mContext = context;
}
public FileListAdapter getFileListAdapter(){
if(null == mFileListAdapter){
mFileList = new ArrayList<File>();
mFileListAdapter = new FileListAdapter(mContext, mFileList, R.layout.file_list_item);
}
return mFileListAdapter;
}
public void clearDevice(){
if(null != mDeviceList){
mDeviceList.clear();
}
}
public void addDevice(BluetoothDevice bluetoothDevice){
mDeviceList.add(bluetoothDevice);
}
public void changeDevice(int listId, BluetoothDevice bluetoothDevice){
mDeviceList.remove(listId);
mDeviceList.add(listId, bluetoothDevice);
}
public void updateFileListAdapter(String path){
mFileList.clear();
mFileList.addAll(getFileList(path));
if(null == mainHandler){
mainHandler = new Handler(mContext.getMainLooper());
}
mainHandler.post(new Runnable() {
#Override
public void run() {
mFileListAdapter.notifyDataSetChanged();
}
});
}
public List<BluetoothDevice> getDeviceList() {
return mDeviceList;
}
public static List<File> getFileList(String path){
List<File> fileList = new ArrayList<File>();
File[] files = new File(path).listFiles();
if(files.length > 0){
List<File> allFolder = new ArrayList<File>();
List<File> allFile = new ArrayList<File>();
for(File file : files){
if(file.isFile()){
allFile.add(file);
}else {
allFolder.add(file);
}
}
fileList.addAll(allFolder);
fileList.addAll(allFile);
}
return fileList;
}
}
my xml is
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.android.BluetoothChat"
android:versionCode="1"
android:versionName="1.0" xmlns:tools="http://schemas.android.com/tools">
<uses-sdk
android:minSdkVersion="6"
android:targetSdkVersion="18" tools:ignore="OldTargetApi"/>
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />
<uses-permission android:name="android.permission.BLUETOOTH" />
<uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<application
android:allowBackup="true"
android:label="#string/app_name"
android:icon="#drawable/ic_launcher"
android:theme="#style/AppTheme" >
<activity android:name="com.example.android.BluetoothChat.BluetoothChat"
android:label="#string/app_name"
>
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name="com.example.android.BluetoothChat.DeviceListActivity"
android:label="#string/select_device"
android:theme="#android:style/Theme.Dialog"
/>
<activity android:name="com.example.android.BluetoothFileTran.FileTranActivity"
android:label="#string/select_file"
android:theme="#android:style/Theme.Dialog"
/>
</application>
</manifest>
Register in the AndroidManifest the BluetoothFileTran class as application name in application tag:
<application
android:allowBackup="true"
android:name="com.example.android.BluetoothFileTran"
...
Without this, the BluetoothFileTran will not be loaded, and onCreate will never invoked.
This will return a null reference in BluetoothApplication.getInstance(), which are causing your NullPointerException.
Reference
Notice: Your package in manifest, package="com.example.android.BluetoothChat" is different from the package that BluetoothFileTran is located (not in one of childs). I recommend you to use the package com.example.android instead of com.example.android.BluetoothChat in manifest tag.
I need to add a search bar in my app, but all the tutorials I tried is not working. Because I want this bar to return the values of my ListView imported from Excel (I applied in a way that the Activity shows the names of people). My ListView is imported from Excel, not created in-app code.
That is, when I search for "A" all the names of the ListView with "A" appears when I search "Arn", appear the names containing "Arn" (E.g. Arnold Clinton).
This is the code of TabelaActivity.java:
package com.akzonobel.malote.tabela;
import com.akzonobel.malote.R;
import android.app.Activity;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.widget.EditText;
import android.widget.ListView;
public class TabelaActivity extends Activity {
CSVAdapter mAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_tabela);
ListView mList = (ListView)findViewById(R.id.mList);
mAdapter = new CSVAdapter(this, -1);
mList.setAdapter(mAdapter);
}
}
This is the code of CSVAdapter.java:
package com.akzonobel.malote.tabela;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import android.content.Context;
import android.graphics.Color;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;
public class CSVAdapter extends ArrayAdapter<State>{
Context ctx;
public CSVAdapter(Context context, int textViewResourceId) {
super(context, textViewResourceId);
this.ctx = context;
loadArrayFromFile();
}
#Override
public View getView(final int pos, View convertView, final ViewGroup parent){
TextView mView = (TextView)convertView;
if(null == mView){
mView = new TextView(parent.getContext());
mView.setTextSize(19);
mView.setTextColor(Color.WHITE);
}
mView.setText(getItem(pos).getName());
return mView;
}
private void loadArrayFromFile(){
try {
InputStream is = ctx.getAssets().open("states.csv");
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
String line;
while ((line = reader.readLine()) != null) {
State cur = new State();
cur.setName(line);
this.add(cur);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
This is the code of State.java:
package com.akzonobel.malote.tabela;
public class State {
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
I tried to apply this search bar:
EditText inputSearch;
inputSearch = (EditText) findViewById(R.id.inputSearch);
inputSearch.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence cs, int arg1, int arg2, int arg3) {
// When user changed the Text
TabelaActivity.this.mAdapter.getFilter().filter(cs);
}
#Override
public void beforeTextChanged(CharSequence arg0, int arg1, int arg2,
int arg3) {
// TODO Auto-generated method stub
}
#Override
public void afterTextChanged(Editable arg0) {
// TODO Auto-generated method stub
}
});
}
The search bar works, can you enter. But when I type the value... it just does not return anything, goes blank. Any help? How to make it work? Or is there another easy way to make a search bar? Can the ActionBar.. the important thing is it works.
Then I tried to apply the getFilter in CSVAdapter, but then when I try to use the bar with this getFilter, it crashes and closes alone.
This is the code I applied getFilter:
private List<State> allModelItemsArray;
private List<State> filteredModelItemsArray;
private Filter filter;
#Override
public Filter getFilter() {
if (filter == null){
filter = new ModelFilter();
}
return filter;
}
private class ModelFilter extends Filter
{
#Override
protected FilterResults performFiltering(CharSequence constraint) {
constraint = constraint.toString().toLowerCase();
FilterResults result = new FilterResults();
if(constraint != null && constraint.toString().length() > 0)
{
ArrayList<State> filteredItems = new ArrayList<State>();
for(int i = 0, l = allModelItemsArray.size(); i < l; i++)
{
State m = allModelItemsArray.get(i);
if(m.getName().toLowerCase().contains(constraint))
filteredItems.add(m);
}
result.count = filteredItems.size();
result.values = filteredItems;
}
else
{
synchronized(this)
{
result.values = allModelItemsArray;
result.count = allModelItemsArray.size();
}
}
return result;
}
#SuppressWarnings("unchecked")
#Override
protected void publishResults(CharSequence constraint, FilterResults results) {
filteredModelItemsArray = (ArrayList<State>)results.values;
notifyDataSetChanged();
clear();
for(int i = 0, l = filteredModelItemsArray.size(); i < l; i++)
add(filteredModelItemsArray.get(i));
notifyDataSetInvalidated();
}
}
And when this is active getFilter, besides closing, it gives the following error in LogCat:
07-13 08:32:52.925: W/Filter(30254): An exception occured during performFiltering()!
07-13 08:32:52.925: W/Filter(30254): java.lang.NullPointerException
07-13 08:32:52.925: W/Filter(30254): at com.akzonobel.malote.tabela.CSVAdapter$ModelFilter.performFiltering(CSVAdapter.java:129)
07-13 08:32:52.925: W/Filter(30254): at android.widget.Filter$RequestHandler.handleMessage(Filter.java:234)
07-13 08:32:52.925: W/Filter(30254): at android.os.Handler.dispatchMessage(Handler.java:99)
07-13 08:32:52.925: W/Filter(30254): at android.os.Looper.loop(Looper.java:137)
07-13 08:32:52.925: W/Filter(30254): at android.os.HandlerThread.run(HandlerThread.java:60)
07-13 08:33:14.856: D/AndroidRuntime(30254): Shutting down VM
07-13 08:33:14.856: W/dalvikvm(30254): threadid=1: thread exiting with uncaught exception (group=0x41101930)
07-13 08:33:14.876: E/AndroidRuntime(30254): FATAL EXCEPTION: main
07-13 08:33:14.876: E/AndroidRuntime(30254): java.lang.NullPointerException
07-13 08:33:14.876: E/AndroidRuntime(30254): at com.akzonobel.malote.tabela.CSVAdapter$ModelFilter.publishResults(CSVAdapter.java:156)
07-13 08:33:14.876: E/AndroidRuntime(30254): at android.widget.Filter$ResultsHandler.handleMessage(Filter.java:282)
07-13 08:33:14.876: E/AndroidRuntime(30254): at android.os.Handler.dispatchMessage(Handler.java:99)
07-13 08:33:14.876: E/AndroidRuntime(30254): at android.os.Looper.loop(Looper.java:137)
07-13 08:33:14.876: E/AndroidRuntime(30254): at android.app.ActivityThread.main(ActivityThread.java:5283)
07-13 08:33:14.876: E/AndroidRuntime(30254): at java.lang.reflect.Method.invokeNative(Native Method)
07-13 08:33:14.876: E/AndroidRuntime(30254): at java.lang.reflect.Method.invoke(Method.java:511)
07-13 08:33:14.876: E/AndroidRuntime(30254): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1102)
07-13 08:33:14.876: E/AndroidRuntime(30254): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:869)
07-13 08:33:14.876: E/AndroidRuntime(30254): at dalvik.system.NativeStart.main(Native Method)
Add a constructor to the State class:
public State(String name) {
this.name = name;
}
Don't use the global allModelItemsArray and filteredItemsArray, get rid of them.
Then change your performFiltering function like this:
#Override
protected FilterResults performFiltering(CharSequence constraint) {
constraint = constraint.toString().toLowerCase();
FilterResults result = new FilterResults();
if(constraint != null && constraint.toString().length() > 0)
{
ArrayList<State> filteredItems = new ArrayList<State>();
for(int i = 0, l = getCount(); i < l; i++)
{
State m = getItem(i);
if(m.getName().toLowerCase().contains(constraint))
filteredItems.add(m);
}
result.count = filteredItems.size();
result.values = filteredItems;
}
else
{
ArrayList<State> allItems = new ArrayList<State>();
for(int i = 0, l = getCount(); i < l; i++)
{
State m = getItem(i);
allItems.add(m);
}
synchronized(this)
{
result.values = allItems;
result.count = allItems.size();
}
}
return result;
}
This will work much better and is proper way to fix this.
i am creating an app for my final year project at uni.. i am trying to get an rss feed working.. My issue at the moment is that i created a project (RSSActivity) and got the RSS feeds to work. I then copy and pasted all the files (5 classes and 2 layouts) into the appropriate places. There were a few errors: R cannot be found, but this was easily fixed by changing the package to that of the project (football_app). What i am tring to do is be able to click on a button called 'News' and the news appears.. the problem that i am have is that the when i now click on the 'News' button, it say 'Unfortunately football app has stopped'.. i have tried every single class in the intent, and changed the intent activity name appropriately.. can anyone help me.. code below...
/////////////// HttpFeedSource.java
package com.julian.football_app;
import java.util.ArrayList;
import java.util.List;
class HttpFeedSource implements FeedSource {
protected static final String URL = "http://www.skysports.com/rss/0,20514,11661,00.xml";
public List<RSSItem> getFeed() {
List<RSSItem> itemList = new ArrayList<RSSItem>();
NewsParser parser = new NewsParser(URL);
parser.parse();
NewsParser.RssFeed feed = parser.getFeed();
for (NewsParser.Item i : feed.getItems()) {
itemList.add(new RSSItem(i.getUrl(), i.getTitle(), i.getDescription(), i.getimageUrl()));
}
return itemList;
}
}
////////////////////// FeedSource.java
package com.julian.football_app;
import java.util.List;
interface FeedSource {
List<RSSItem> getFeed();
}
<code>
/////////////////////////////////////////////////////////////////////////////////////////// //MockFeedSource.java
package com.julian.football_app;
import java.util.ArrayList;
import java.util.List;
class MockFeedSource implements FeedSource {
public List<RSSItem> getFeed() {
RSSItem item;
final List<RSSItem> items = new ArrayList<RSSItem>();
item = new RSSItem("Android Workshop er gøy", "http://www.ap.no", " this is the desc", "");
items.add(item);
item = new RSSItem("Android Workshop er gøy 2", "http://www.ap.no", "this is the desc", "");
items.add(item);
item = new RSSItem("Android Workshop er gøy3", "http://www.ap.no", "this is the desc", "");
items.add(item);
return items;
}
}
</code>
/////////////////////////////////////////////////////////////////////////////////////////// NewsParser.java
package com.julian.football_app;
import org.xml.sax.Attributes;
import org.xml.sax.InputSource;
import org.xml.sax.helpers.DefaultHandler;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import java.io.InputStream;
import java.net.URL;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Locale;
class NewsParser extends DefaultHandler {
public static SimpleDateFormat sdf = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss zzz", Locale.ENGLISH);
private String urlString;
private RssFeed rssFeed;
private StringBuilder text;
private Item item;
private boolean imgStatus;
public NewsParser(String url) {
this.urlString = url;
this.text = new StringBuilder();
}
public void parse() {
InputStream urlInputStream = null;
SAXParserFactory spf;
SAXParser sp;
try {
URL url = new URL(this.urlString);
urlInputStream = url.openConnection().getInputStream();
InputSource is = new InputSource(urlInputStream);
is.setEncoding("ISO-8859-1");
spf = SAXParserFactory.newInstance();
if (spf != null) {
sp = spf.newSAXParser();
sp.parse(is, this);
}
} catch (Exception e) {
throw new RuntimeException(e);
} finally {
try {
if (urlInputStream != null) urlInputStream.close();
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
public RssFeed getFeed() {
return (this.rssFeed);
}
public void startElement(String uri, String localName, String qName,
Attributes attributes) {
if (qName.equalsIgnoreCase("channel"))
this.rssFeed = new RssFeed();
else if (qName.equalsIgnoreCase("item") && (this.rssFeed != null)) {
this.item = new Item();
this.rssFeed.addItem(this.item);
} else if (qName.equalsIgnoreCase("image") && (this.rssFeed != null))
this.imgStatus = true;
}
public void endElement(String uri, String localName, String qName) {
if (this.rssFeed == null)
return;
if (qName.equalsIgnoreCase("item"))
this.item = null;
else if (qName.equalsIgnoreCase("image"))
this.imgStatus = false;
else if (qName.equalsIgnoreCase("title")) {
if (this.item != null) this.item.title = this.text.toString().trim();
else if (this.imgStatus) this.rssFeed.imageTitle = this.text.toString().trim();
else this.rssFeed.title = this.text.toString().trim();
} else if (qName.equalsIgnoreCase("link")) {
if (this.item != null) this.item.link = this.text.toString().trim();
else if (this.imgStatus) this.rssFeed.imageLink = this.text.toString().trim();
else this.rssFeed.link = this.text.toString().trim();
} else if (qName.equalsIgnoreCase("description")) {
if (this.item != null) this.item.description = this.text.toString().trim();
else this.rssFeed.description = this.text.toString().trim();
} else if (qName.equalsIgnoreCase("url") && this.imgStatus)
this.rssFeed.imageUrl = this.text.toString().trim();
else if (qName.equalsIgnoreCase("language"))
this.rssFeed.language = this.text.toString().trim();
else if (qName.equalsIgnoreCase("generator"))
this.rssFeed.generator = this.text.toString().trim();
else if (qName.equalsIgnoreCase("copyright"))
this.rssFeed.copyright = this.text.toString().trim();
else if (qName.equalsIgnoreCase("pubDate") && (this.item != null)) {
try {
this.item.pubDate = sdf.parse(this.text.toString().trim());
} catch (ParseException e) {
throw new RuntimeException();
}
} else if (qName.equalsIgnoreCase("category") && (this.item != null))
this.rssFeed.addItem(this.text.toString().trim(), this.item);
this.text.setLength(0);
}
public void characters(char[] ch, int start, int length) {
this.text.append(ch, start, length);
}
public static class RssFeed {
public String title;
public String description;
public String link;
public String language;
public String generator;
public String copyright;
public String imageUrl;
public String imageTitle;
public String imageLink;
private ArrayList<Item> items;
private HashMap<String, ArrayList<Item>> category;
public void addItem(Item item) {
if (this.items == null)
this.items = new ArrayList<Item>();
this.items.add(item);
}
public void addItem(String category, Item item) {
if (this.category == null)
this.category = new HashMap<String, ArrayList<Item>>();
if (!this.category.containsKey(category))
this.category.put(category, new ArrayList<Item>());
this.category.get(category).add(item);
}
public ArrayList<Item> getItems() {
return items;
}
}
public static class Item implements Comparable<Item> {
public String title;
public String description;
public String link;
public Date pubDate;
private String url;
private String imageUrl;
public String toString() {
return (this.title + ": ");
}
public int compareTo(Item o) {
return (int) (o.pubDate.getTime() - pubDate.getTime());
}
public Date getPubDate() {
return pubDate;
}
public String getDescription() {
return description;
}
public String getTitle() {
return title;
}
public String getUrl() {
return url;
}
public String getimageUrl() {
return imageUrl;
}
}
}
package com.julian.football_app;
import com.julian.football_app.R;
import android.app.Activity;
import android.os.Bundle;
import android.widget.ListView;
public class RSSActivity extends Activity {
/**
* Called when the activity is first created.
*/
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main2);
ListView rssItemList = (ListView) findViewById(R.id.rssListview);
FeedSource feedSource = new HttpFeedSource();
RSSItemAdapter adapter = new RSSItemAdapter(this, R.layout.rssitem, feedSource.getFeed());
rssItemList.setAdapter(adapter);
}
}
/////////RssItem
package com.julian.football_app;
import java.util.Date;
class RSSItem {
private String url;
private String title;
private String description;
private String imageUrl;
private Date pubDate;
public RSSItem() {
}
public RSSItem(String url, String title, String description, String imageUrl) {
this.url = url;
this.title = title;
this.description = description;
this.imageUrl = imageUrl;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getDescription() {
return description;
}
public void setDesc(String description) {
this.description = description;
}
public void setImageUrl(String imageUrl) {
this.imageUrl = imageUrl;
}
public String getimageUrl() {
return imageUrl;
}
public void setpubDate(Date pubDate){
this.pubDate = pubDate;
}
public Date getpubDate(){
return pubDate;
}
}
////////////////// RssItemAdaptor
package com.julian.football_app;
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;
import com.julian.football_app.R;
class RSSItemAdapter extends ArrayAdapter<RSSItem> {
private final Context context;
public RSSItemAdapter(Context context, int textViewResourceId,
List<RSSItem> items) {
super(context, textViewResourceId, items);
this.context = context;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View v = convertView;
if (v == null) {
LayoutInflater vi = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = vi.inflate(R.layout.rssitem, null);
}
final RSSItem item = getItem(position);
TextView title = (TextView) v.findViewById(R.id.title);
TextView desc = (TextView) v.findViewById(R.id.description);
TextView url = (TextView) v.findViewById(R.id.url);
// this is what is viewed
title.setText(item.getTitle());
desc.setText(item.getDescription());
url.setText(item.getimageUrl());
return v;
}
}
///This is the button i want to display the Rss Feed
package com.julian.football_app;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
public class Menu extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.menu);
//setting the buttons
Button btnews1 = (Button) findViewById(R.id.news_1);
btnews1.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
Intent news1intent = new Intent(Menu.this, news_1.class);
Menu.this.startActivity(news1intent);
}
});
Thank you for looking at my code... It would be much appreciated if someone could help me :) (i know its says news_1.class in the intent.. its only cuz i tried everything and went back to original state..)
These are the errors that appear in the LogCat:
03-23 13:54:16.118: E/AndroidRuntime(553): FATAL EXCEPTION: main
03-23 13:54:16.118: E/AndroidRuntime(553): at android.app.Instrumentation.checkStartActivityResult(Instrumentation.java:1508)
03-23 13:54:16.118: E/AndroidRuntime(553): at android.app.Instrumentation.execStartActivity(Instrumentation.java:1384)
03-23 13:54:16.118: E/AndroidRuntime(553): at android.app.Activity.startActivityForResult(Activity.java:3190)
03-23 13:54:16.118: E/AndroidRuntime(553): at android.app.Activity.startActivity(Activity.java:3297)
03-23 13:54:16.118: E/AndroidRuntime(553): at com.julian.football_app.Menu$1.onClick(Menu.java:24)
03-23 13:54:16.118: E/AndroidRuntime(553): at android.view.View.performClick(View.java:3460)
03-23 13:54:16.118: E/AndroidRuntime(553): at android.view.View$PerformClick.run(View.java:13955)
03-23 13:54:16.118: E/AndroidRuntime(553): at android.os.Handler.handleCallback(Handler.java:605)
03-23 13:54:16.118: E/AndroidRuntime(553): at android.os.Handler.dispatchMessage(Handler.java:92)
03-23 13:54:16.118: E/AndroidRuntime(553): at android.os.Looper.loop(Looper.java:137)
03-23 13:54:16.118: E/AndroidRuntime(553): at android.app.ActivityThread.main(ActivityThread.java:4340)
03-23 13:54:16.118: E/AndroidRuntime(553): at java.lang.reflect.Method.invokeNative(Native Method)
03-23 13:54:16.118: E/AndroidRuntime(553): at java.lang.reflect.Method.invoke(Method.java:511)
03-23 13:54:16.118: E/AndroidRuntime(553): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784)
03-23 13:54:16.118: E/AndroidRuntime(553): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551)
03-23 13:54:16.118: E/AndroidRuntime(553): at dalvik.system.NativeStart.main(Native Method)
It sounds like the app is experiencing an exception. To find the cause you need to use LogCat to look at the exception details, which will show you where in your code there is a problem.
See how your application goes off the rails right around:
E/AndroidRuntime(553): at android.app.Activity.startActivity(Activity.java:3297) 03-23 13:54:16.118:
E/AndroidRuntime(553): at com.julian.football_app.Menu$1.onClick(Menu.java:24) 03-23 13:54:16.118:
My feeling is this isn't about the RSS at all. I think you need to fix the Intent navigation between the Activities in your application. You might try blocking out all the behavior from your Activities (comment out the interesting bits of onCreate() or whatever) and make sure you can navigate smoothly between Activities. Then re-enable the Activities and make sure they don't blow up when you enter them.
See also MH's comment about checking that all Activities are in your Manifest.
And take out that line that says:
import com.julian.football_app.R;
If you can't get your code to compile without including a .R, then you're doing something wrong. Try saving all the source files, deleting the contents of your gen directory, and selecting Project > Clean.