Attempt to invoke virtual method 'void android.widget.GridView.setAdapter(android.widget.ListAdapter)' on a null object reference - Android Activity - android-adapter

I have been trying to develop an app, whereby clicking on the Image button, it draws the whole screen using bitmap and saves it in a directory, and will show the complete list of all images in that directory by passing the intent....The above two steps will be done with a single click, where I am able to save the bitmap in the specified directory, but not able to retrieve the images in a custom grid view gallery...posting the code which I wrote
public class Share extends SecureActivity {
private int count;
Context context;
private Bitmap[] thumbnails;
private boolean[] thumbnailsselection;
private String[] arrPath;
private ImageAdapter imageAdapter = null;
ArrayList<String> f = new ArrayList<String>();// list of file paths
File[] listFile;
GridView imageGrid;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
getFromSdcard();
imageGrid = (GridView) findViewById(R.id.imageGrid);
imageAdapter = new ImageAdapter();
imageGrid.setAdapter(imageAdapter);
}
public void getFromSdcard()
{
File file= new File(android.os.Environment.getExternalStorageDirectory(),"ScreenShots");
if (file.isDirectory())
{
listFile = file.listFiles();
for (int i = 0; i < listFile.length; i++)
{
f.add(listFile[i].getAbsolutePath());
}
}
String size = String.valueOf(f.size());
String name = f.get(f.size()-1);
/*// ImageView imagegrid = (ImageView) findViewById(R.id.PhoneImageGrid);
try{
Bitmap bm = BitmapFactory.decodeFile(name);
bm.prepareToDraw();
imagegrid.setImageBitmap(bm);
}
catch(Exception e)
{
e.printStackTrace();
}
Log.d(size,"number of files");
Log.d(name,"image file");
*/
}
public class ImageAdapter extends BaseAdapter {
private LayoutInflater mInflater;
public ImageAdapter() {
mInflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
public int getCount() {
return f.size();
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if (convertView == null) {
holder = new ViewHolder();
convertView = mInflater.inflate(
R.layout.gallery_item, null);
holder.imageview = (ImageView) convertView.findViewById(R.id.thumbImage);
convertView.setTag(holder);
}
else {
holder = (ViewHolder) convertView.getTag();
}
Bitmap myBitmap = BitmapFactory.decodeFile(f.get(position));
holder.imageview.setImageBitmap(myBitmap);
return convertView;
}
}
class ViewHolder {
ImageView imageview;
}
with this, I am getting below error
FATAL EXCEPTION: main
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.edutor.ignitor/com.edutor.ignitor.EdutorShare}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.GridView.setAdapter(android.widget.ListAdapter)' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2491)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2556)
at android.app.ActivityThread.access$800(ActivityThread.java:170)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1441)
at android.os.Handler.dispatchMessage(Handler.java:111)
at android.os.Looper.loop(Looper.java:194)
at android.app.ActivityThread.main(ActivityThread.java:5568)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:955)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:750)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.GridView.setAdapter(android.widget.ListAdapter)' on a null object reference
at com.edutor.ignitor.EdutorShare.onCreate(EdutorShare.java:43)
at android.app.Activity.performCreate(Activity.java:6041)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1111)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2437)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2556)
at android.app.ActivityThread.access$800(ActivityThread.java:170)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1441)
at android.os.Handler.dispatchMessage(Handler.java:111)
at android.os.Looper.loop(Looper.java:194)
at android.app.ActivityThread.main(ActivityThread.java:5568)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:955)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:750)
can someone please help...where I went wrong

Related

On using swipe refresh in recyclerview my adapter is not getting data when it is refreshing

My Latest fragment
public class Latest extends Fragment {
private RecyclerView recyclerLatest;
private SwipeRefreshLayout swipeRecycler;
private RecyclerView.LayoutManager mLayoutManager;
private List<LatestAdDetails> latestAdDetailsList = new ArrayList<>();
private LatestAdapter latestAdapter;
private LatestAdDetails latestAdDetails,latestAdDetails1;
private JSONObject jsonobject;
private Context context;
private String x;
public Latest() {
}
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View mainView=inflater.inflate(R.layout.latest_fragment,container,false);
recyclerLatest = (RecyclerView) mainView.findViewById(R.id.recycler_latest);
swipeRecycler= (SwipeRefreshLayout)mainView.findViewById(R.id.swipe_recycler_latest);
mLayoutManager = new LinearLayoutManager(getContext(), LinearLayoutManager.VERTICAL, false);
recyclerLatest.setLayoutManager(mLayoutManager);
recyclerLatest.setHasFixedSize(true);
context = getContext();
// url for latest add obtaining
UrlConstants.latest_ad_obtained= UrlConstants.latest_ad+ AppController.getString(getActivity().getApplicationContext(),"country_id")+"/"+AppController.getString(getActivity().getApplicationContext(),"city_id");
latestAdapter = new LatestAdapter(latestAdDetailsList);
recyclerLatest.setAdapter(latestAdapter);
latestAdd();
swipeRecycler.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
#Override
public void onRefresh(){refreshLatestAd();
}
});
return mainView;
}
private void refreshLatestAd() {
UrlConstants.latset_ad_refresh_obtained=UrlConstants.latest_ad_refresh+
AppController.getString(getActivity().getApplicationContext(),"country_id")+"/"+
AppController.getString(getActivity().getApplicationContext(),"city_id")+"/"+
AppController.getString(getActivity().getApplicationContext(),"refresh_ad")+"/"+0;
LatestRefreshHandler latestRefreshHandler = new LatestRefreshHandler("latestRefreshADD");
latestRefreshHandler.executeAsStringRequest(new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.e("response", response);
JSONArray jsonarray = null;
try {
jsonarray = new JSONArray(response);
} catch (JSONException e) {
e.printStackTrace();
}
for (int i = 0; i < jsonarray.length(); i++) {
try {
jsonobject = jsonarray.getJSONObject(i);
if (jsonobject.getString("default_photo").isEmpty()) {
x = UrlConstants.default_photo;
} else {
x = jsonobject.getString("default_photo");
}
Log.e("x", x);
latestAdapter.clear();
int Ad_id_refresh = jsonarray.getJSONObject(jsonarray.length()).getInt("id");
AppController.setString(context,"refresh_ad", String.valueOf(Ad_id_refresh));
latestAdDetails = new LatestAdDetails(
jsonobject.getInt("id"),
jsonobject.getInt("cityid"),
jsonobject.getInt("price"),
jsonobject.getInt("type"),
jsonobject.getInt("comments"),
jsonobject.getInt("categoryid"),
jsonobject.getInt("MainCategoryID"),
jsonobject.getInt("created"),
jsonobject.getInt("views"),
jsonobject.getString("title"),
jsonobject.getString("default_photo"),
jsonobject.getString("CityName"),
jsonobject.getString("CategoryName"),
jsonobject.getString("storeid"),
jsonobject.getString("currency"),
jsonobject.getString("description"),
jsonobject.getDouble("Latitude"),
jsonobject.getDouble("Longitude")
);
latestAdDetailsList.add(latestAdDetails);
} catch (JSONException e) {
e.printStackTrace();
}
}
latestAdapter.addAll(latestAdDetailsList);
latestAdapter.notifyDataSetChanged();
recyclerLatest.setAdapter(latestAdapter);
swipeRecycler.setRefreshing(false);
}
}, new BaseRequest.ErrorResponseCallback() {
#Override
public void onError(Exception exception) {
}
});
}
private void latestAdd() {
LatestRequestHandler latestHandler = new LatestRequestHandler("latestADD");
latestHandler.executeAsStringRequest(new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.e("response", response);
JSONArray jsonarray = null;
try {
jsonarray = new JSONArray(response);
} catch (JSONException e) {
e.printStackTrace();
}
for (int i = 0; i < jsonarray.length(); i++) {
try {
jsonobject = jsonarray.getJSONObject(i);
if (jsonobject.getString("default_photo").isEmpty()) {
x = UrlConstants.default_photo;
} else {
x = jsonobject.getString("default_photo");
}
Log.e("x", x);
int Ad_id_refresh = jsonarray.getJSONObject(1).getInt("id");
AppController.setString(context,"refresh_ad", String.valueOf(Ad_id_refresh));
latestAdDetails = new LatestAdDetails(
jsonobject.getInt("id"),
jsonobject.getInt("cityid"),
jsonobject.getInt("price"),
jsonobject.getInt("type"),
jsonobject.getInt("comments"),
jsonobject.getInt("categoryid"),
jsonobject.getInt("MainCategoryID"),
jsonobject.getInt("created"),
jsonobject.getInt("views"),
jsonobject.getString("title"),
jsonobject.getString("default_photo"),
jsonobject.getString("CityName"),
jsonobject.getString("CategoryName"),
jsonobject.getString("storeid"),
jsonobject.getString("currency"),
jsonobject.getString("description"),
jsonobject.getDouble("Latitude"),
jsonobject.getDouble("Longitude")
);
latestAdDetailsList.add(latestAdDetails);
} catch (JSONException e) {
e.printStackTrace();
}
}
latestAdapter.notifyDataSetChanged();
}
}, new BaseRequest.ErrorResponseCallback() {
#Override
public void onError(Exception exception) {
}
});
}}
my Adapter class
public class LatestAdapter extends RecyclerView.Adapter<LatestAdapter.MyViewHolder> {
private ImageLoader imageLoader;
private Context context;
private String text;
private List<LatestAdDetails> latestAddDetailsList;
public LatestAdapter(List<LatestAdDetails> latestAddDetailsList) {
this.latestAddDetailsList = latestAddDetailsList;
}
public class MyViewHolder extends RecyclerView.ViewHolder {
private TextView txtTitle, txtDescription, txtCityName, txtPrice, txtCategory, txtHour, txtPhotoNo;
private NetworkImageView imgPhoto;
public MyViewHolder(View itemView) {
super(itemView);
txtTitle = (TextView) itemView.findViewById(R.id.txt_title_fad);
txtDescription = (TextView) itemView.findViewById(R.id.description_fad);
txtCityName = (TextView) itemView.findViewById(R.id.city_name_fad);
txtPrice = (TextView) itemView.findViewById(R.id.price_fad);
txtCategory = (TextView) itemView.findViewById(R.id.category_fad);
txtHour = (TextView) itemView.findViewById(R.id.hours_fad);
txtPhotoNo = (TextView) itemView.findViewById(R.id.txt_photo_no_fad);
imgPhoto = (NetworkImageView) itemView.findViewById(R.id.img_photo_lod_fad);
}
}
public void clear() {
latestAddDetailsList.clear();
notifyDataSetChanged();
}// Add a list of items
public void addAll(List<LatestAdDetails> list) {
latestAddDetailsList.addAll(list);
notifyDataSetChanged();
}
#Override
public LatestAdapter.MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext()).inflate(R.layout.featured_ad_adapter_layout, parent, false);
return new MyViewHolder(itemView);
}
#Override
public void onBindViewHolder(LatestAdapter.MyViewHolder holder, int position) {
LatestAdDetails latestAddDetails = latestAddDetailsList.get(position);
holder.txtTitle.setText(translate(latestAddDetails.getTitle()));
holder.txtDescription.setText(translate(latestAddDetails.getDescription()));
holder.txtCityName.setText(translate(latestAddDetails.getCityName()));
holder.txtPrice.setText(Integer.toString(latestAddDetails.getPrice()));
holder.txtCategory.setText(translate(latestAddDetails.getCategoryName()));
holder.txtHour.setText(Integer.toString(latestAddDetails.getCreated()));
holder.txtPhotoNo.setText(Integer.toString(0) + " photos ");
try {
imageLoader = VolleyHandler.getImageLoader();
} catch (Exception e) {
e.printStackTrace();
}
holder.imgPhoto.setImageUrl(latestAddDetails.getDefault_photo(), imageLoader);
}
#Override
public int getItemCount() {
Log.e("size", String.valueOf(latestAddDetailsList.size()));
return latestAddDetailsList.size();
}
private String translate(String myString) {
try {
myString = myString.replace("\n", "").replace("\r", "");
byte[] utf8Bytes = myString.getBytes("UTF8");
text = new String(utf8Bytes, "UTF8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
return text;
}}
on refreshing adapter size is zero,but getting json correctly,but not adding to adapter,and the recycler view is not showing new data,please help me ,the json is giving 10 datas on every swipe but it is not getting added to recyclerview
It seems like a logical bug :
In method : refreshLatestAd(), Remove these line :
latestAdapter.clear();
latestAdapter.addAll(latestAdDetailsList);
and
recyclerLatest.setAdapter(latestAdapter); // It need not be set again.
Let me know if it helps.
latestAdapter.notifyDataSetChanged() is sufficient to notify the
adapter that the data is changed. Always modify the list
[latestAdDetailsList] which is being set to adapter, this is the sure
shot way to make the changes reflect when you call notifyDataSetChanged.

How to check whether an item exists in the dynamodb table?

I am making an android app with login via facebook and custom signup. I am using AWS dynamodb to store the user data.
I am able to store the data from facebook and custom signup but unable to scan that data. Actually I want whenever a user come back to login with his/her credentials either custom or facebook, the app should check whether the entered fields present in the table or not. If it is unavailable then app will ask user to signup first.
MainActivity
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
private static final String TAG = "MainActivity";
Button login;
TextView signup;
TextView help;
EditText etUsername;
EditText etPassword;
String email;
String pass;
String email1;
String pass1;
private CognitoCachingCredentialsProvider credentialsProvider;
private CallbackManager callbackManager;
private LoginButton loginButton;
private ImageButton btnLoginFb;
private ProgressDialog progressDialog;
User user;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
FacebookSdk.sdkInitialize(getApplicationContext());
setContentView(R.layout.activity_main);
etUsername = (EditText) findViewById(R.id.etUsername);
etPassword = (EditText) findViewById(R.id.etPassword);
login = (Button) findViewById(R.id.loginbutton);
signup = (TextView) findViewById(R.id.textViewsignup);
help = (TextView) findViewById(R.id.textViewHelp);
etUsername = (EditText) findViewById(R.id.etUsername);
etPassword = (EditText) findViewById(R.id.etPassword);
login.setOnClickListener(this);
signup.setOnClickListener(this);
help.setOnClickListener(this);
Context mContext = this.getApplicationContext();
credentialsProvider = new CognitoCachingCredentialsProvider(
mContext, // get the context for the current activity
"us-east-1:*******************************",
Regions.US_EAST_1
);
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.loginbutton:
email = etUsername.getText().toString();
pass = etPassword.getText().toString();
AmazonDynamoDBClient ddbClient = new AmazonDynamoDBClient(credentialsProvider);
DynamoDBMapper mapper = new DynamoDBMapper(ddbClient);
if (email != null && pass != null) {
Intent slideactivity = new Intent(MainActivity.this, Welcome.class);
Bundle bndlanimation =
ActivityOptions.makeCustomAnimation(getApplicationContext(), R.anim.animation, R.anim.animation2).toBundle();
startActivity(slideactivity, bndlanimation);
return;
}
else {
AlertDialog alertDialog = new AlertDialog.Builder(
MainActivity.this).create();
// Setting Dialog Title
alertDialog.setTitle("Oops");
// Setting Dialog Message
alertDialog.setMessage("No data found. You have to signup first!!!");
// Setting Icon to Dialog
//alertDialog.setIcon(R.drawable.tick);
// Setting OK Button
alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// Write your code here to execute after dialog closed
startActivity(new Intent(MainActivity.this, SignUp.class));
}
});
// Showing Alert Message
alertDialog.show();
}
break;
case R.id.textViewsignup:
Intent slideactivity = new Intent(MainActivity.this, SignUp.class);
Bundle bndlanimation =
ActivityOptions.makeCustomAnimation(getApplicationContext(), R.anim.animation, R.anim.animation2).toBundle();
startActivity(slideactivity, bndlanimation);
break;
case R.id.textViewHelp:
Intent slideactivity1 = new Intent(MainActivity.this, LoginHelp.class);
Bundle bndlanimation1 =
ActivityOptions.makeCustomAnimation(getApplicationContext(), R.anim.animation, R.anim.animation2).toBundle();
startActivity(slideactivity1, bndlanimation1);
break;
}
}
#Override
protected void onResume() {
super.onResume();
callbackManager = CallbackManager.Factory.create();
loginButton = (LoginButton) findViewById(R.id.login_button);
loginButton.setReadPermissions("public_profile", "email", "user_friends");
btnLoginFb = (ImageButton) findViewById(R.id.btnLoginFb);
btnLoginFb.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
progressDialog = new ProgressDialog(MainActivity.this);
progressDialog.setMessage("Loading...");
progressDialog.show();
loginButton.performClick();
loginButton.setPressed(true);
loginButton.invalidate();
loginButton.registerCallback(callbackManager, mCallBack);
loginButton.setPressed(false);
loginButton.invalidate();
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
callbackManager.onActivityResult(requestCode, resultCode, data);
}
private FacebookCallback<LoginResult> mCallBack = new FacebookCallback<LoginResult>() {
#Override
public void onSuccess(LoginResult loginResult) {
progressDialog.dismiss();
// App code
GraphRequest request = GraphRequest.newMeRequest(
loginResult.getAccessToken(),
new GraphRequest.GraphJSONObjectCallback() {
#Override
public void onCompleted(
JSONObject object,
GraphResponse response) {
Log.e("response: ", response + "");
try {
user = new User();
user.facebookID = object.getString("id").toString();
pass = user.facebookID;
Log.e(pass, "id");
user.email = object.getString("email").toString();
email = user.email;
Log.e(email, "email");
user.name = object.getString("name").toString();
user.gender = object.getString("gender").toString();
PrefUtils.setCurrentUser(user, MainActivity.this);
} catch (Exception e) {
e.printStackTrace();
}
Toast.makeText(MainActivity.this, "welcome " + user.name, Toast.LENGTH_LONG).show();
Intent intent = new Intent(MainActivity.this, Welcome.class);
startActivity(intent);
finish();
}
});
Bundle parameters = new Bundle();
parameters.putString("fields", "id,name,email,gender, birthday");
request.setParameters(parameters);
request.executeAsync();
new db().execute("");
}
#Override
public void onCancel() {
progressDialog.dismiss();
}
#Override
public void onError(FacebookException e) {
progressDialog.dismiss();
}
};
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
private class db extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... params) {
AmazonDynamoDBClient ddbClient = new AmazonDynamoDBClient(credentialsProvider);
DynamoDBMapper mapper = new DynamoDBMapper(ddbClient);
Item item = new Item();
mapper.load(Item.class, email, pass);
if(item==null)
{
startActivity(new Intent(MainActivity.this,SignUp.class));
}
else{
item.setEmail(email);
item.setPass(pass);
mapper.save(item);
startActivity(new Intent(MainActivity.this,Welcome.class));
}
mapper.load(Item.class, email,pass);
if(item==null) {
startActivity(new Intent(MainActivity.this,SignUp.class));
}
else{
startActivity(new Intent(MainActivity.this,Welcome.class));
}
return "Executed";
}
#Override
protected void onPostExecute(String result) {
}
#Override
protected void onPreExecute() {
}
#Override
protected void onProgressUpdate(Void... values) {
}
}
Logcat:-
java.lang.RuntimeException: An error occurred while executing doInBackground()
at android.os.AsyncTask$3.done(AsyncTask.java:309)
at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:354)
at java.util.concurrent.FutureTask.setException(FutureTask.java:223)
at java.util.concurrent.FutureTask.run(FutureTask.java:242)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:234)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1113)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:588)
at java.lang.Thread.run(Thread.java:818)
Caused by: com.amazonaws.mobileconnectors.dynamodbv2.dynamodbmapper.DynamoDBMappingException: Null key found for public java.lang.String com.ediode.graphics3d.Item.getEmail()
at com.amazonaws.mobileconnectors.dynamodbv2.dynamodbmapper.DynamoDBMapper.getKey(DynamoDBMapper.java:434)
at com.amazonaws.mobileconnectors.dynamodbv2.dynamodbmapper.DynamoDBMapper.load(DynamoDBMapper.java:387)
at com.amazonaws.mobileconnectors.dynamodbv2.dynamodbmapper.DynamoDBMapper.load(DynamoDBMapper.java:466)
at com.amazonaws.mobileconnectors.dynamodbv2.dynamodbmapper.DynamoDBMapper.load(DynamoDBMapper.java:350)
at com.ediode.graphics3d.MainActivity$db.doInBackground(MainActivity.java:339)
at com.ediode.graphics3d.MainActivity$db.doInBackground(MainActivity.java:333)
at android.os.AsyncTask$2.call(AsyncTask.java:295)
at java.util.concurrent.FutureTask.run(FutureTask.java:237)
            at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:234)
            at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1113)
            at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:588)
            at java.lang.Thread.run(Thread.java:818)
I am stuck on this from 4,5 hours. It would be awesome if anyone can help me this stuff.
Thanks
What does your mapper class look like for item? I'm going to assume you have the email as a hash key with no range key because the login username should be unique. You only need the hash key of the object to load it using the load method. This is assuming that there is no range key.
Try using this.
AmazonDynamoDBClient ddbClient = new AmazonDynamoDBClient(credentialsProvider);
DynamoDBMapper mapper = new DynamoDBMapper(ddbClient);
// Use the password as the third parameter if it is a range key.
Item item = mapper.load(Item.class, email1);
if(item == null){
// That email is not in the database
}
else{
// Does exist in database, now compare password.
}

How to display image from url

I have image in server url then i'm passing and displaying in to Card. I have done this in android using LoaderImageView library and displaying but in Glass i'm passing the url link to card. But i got this error "The method addImage(Drawable) in the type CardBuilder is not applicable for the arguments (String)"
Code:
public static Drawable drawableFromUrl(String url) {
Bitmap x;
try {
HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection();
connection.connect();
InputStream input = connection.getInputStream();
x = BitmapFactory.decodeStream(input);
return new BitmapDrawable(x);
} catch(MalformedURLException e) {
//Do something with the exception.
}
catch(IOException ex) {
ex.printStackTrace();
}
return null;
}
View view = new CardBuilder(getBaseContext(), CardBuilder.Layout.TITLE)
.setText("TITLE Card")
// .setIcon(R.drawable.ic_phone)
.addImage(drawableFromUrl(link))
.getView();
From the doc, addImage takes Drawable, int, or Bitmap. It doesn't take String.
You can download image using AsyncTask or thread or whatever you like and convert it to Drawable. Then, you can call addImage.
For example:
// new DownloadImageTask().execute("your url...")
private class DownloadImageTask extends AsyncTask<String, Void, Drawable> {
protected Drawable doInBackground(String... urls) {
String url = urls[0];
return drawableFromUrl(url);
}
protected void onPostExecute(Drawable result) {
// yourCardBuilder.addImage(link)
// or start another activity and use the image there...
}
}
public static Drawable drawableFromUrl(String url) throws IOException {
Bitmap x;
HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection();
connection.connect();
InputStream input = connection.getInputStream();
x = BitmapFactory.decodeStream(input);
return new BitmapDrawable(x);
}
I haven't tested the code but hope you get the idea.
Also see:
How to load an ImageView by URL in Android?
Android Drawable Images from URL
Edit:
private Drawable drawableFromUrl(String url) {
try {
Bitmap bitmap;
HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection();
connection.connect();
InputStream input = connection.getInputStream();
bitmap = BitmapFactory.decodeStream(input);
return new BitmapDrawable(bitmap);
} catch (IOException e) {
return null;
}
}
private class DownloadImageTask extends AsyncTask<String, Void, Drawable> {
protected Drawable doInBackground(String... urls) {
String url = urls[0];
return drawableFromUrl(url);
}
protected void onPostExecute(Drawable result) {
stopSlider();
if(result != null) {
mCardAdapter.setCards(createCard(getBaseContext(), result));
mCardAdapter.notifyDataSetChanged();
}
}
}
See my full example on my GitHub repo. SliderActivity might be helpful for you.

Change Activity into Fragment

I am quite new at Android.
So I am a bit confused of working with fragments.
I have found a very great tutorial.
So I have working code. But it is the layout oft a normal activity.
Then I tried to include it into a navigation drawer.
So the list view with data will only be shown when the menu item has been selected.
On the fragment View there is a never ending loading Dialog.
While debugging I have figured out that the code loads still the data and inserts it into feedItems.
So feedItems is filled correctly.
Now after listAdapter.notifyDataSetChanged() there happens nothing.
So here that is my code:
public class FragmentNews extends ListFragment {
private static final String TAG = FragmentNews.class.getSimpleName();
private ListView listView;
private FeedListAdapter listAdapter;
private List<FeedItem> feedItems;
private String URL_FEED = "http://address.com";
public FragmentNews(){}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onActivityCreated(savedInstanceState);
loadDataForNews();
}
private void loadDataForNews(){
listView = this.getListView();
feedItems = new ArrayList<FeedItem>();
listAdapter = new FeedListAdapter(getActivity(), feedItems);
listView.setAdapter(listAdapter);
// 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);
}
}
// List View Feed
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();
}
}
}
Can the problem be that the inflater of listAdapter is null?
Thanks for help!
Sometimes listAdapter.notifyDataSetChanged() does not work properly.
Try removing
listAdapter = new FeedListAdapter(getActivity(), feedItems);
listView.setAdapter(listAdapter);
from loadDataForNews() and adding in
place of listAdapter.notifyDataSetChanged();

how can add list to a fragment of pageindicator?

i want to add list view to one page of pageindicator the code oof page indicator is :
public class VpiAbsTestActivity extends SherlockFragmentActivity {
private static final String[] CONTENT = new String[] { "This", "Is", "A", "ViewPager", "Demo" };
TestFragmentAdapter mAdapter;
ViewPager mPager;
PageIndicator mIndicator;
public boolean onCreateOptionsMenu(Menu menu) {
SubMenu subMenu1 = menu.addSubMenu("Action Item");
subMenu1.add(0,15, 0, "Sample");
subMenu1.add(0,20, 0,"Menu");
subMenu1.add("Items");
MenuItem subMenu1Item = subMenu1.getItem();
subMenu1Item.setIcon(R.drawable.ic_title_share_default);
subMenu1Item.setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS | MenuItem.SHOW_AS_ACTION_WITH_TEXT);
SubMenu subMenu2 = menu.addSubMenu("Overflow Item");
subMenu2.add("These");
subMenu2.add("Are");
subMenu2.add("Sample");
subMenu2.add("Items");
MenuItem subMenu2Item = subMenu2.getItem();
subMenu2Item.setIcon(R.drawable.ic_compose);
subMenu2Item.setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS | MenuItem.SHOW_AS_ACTION_WITH_TEXT);
return super.onCreateOptionsMenu(menu);
}
public boolean onOptionsItemSelected(MenuItem item) {
// Handle item selection
switch (item.getItemId()) {
case 10:
Toast.makeText(VpiAbsTestActivity.this, "Now "+item.getItemId(), Toast.LENGTH_SHORT).show();
return true;
case 15:
Toast.makeText(VpiAbsTestActivity.this, "Now = "+item.getItemId(), Toast.LENGTH_SHORT).show();
return true;
case 20:
Toast.makeText(VpiAbsTestActivity.this, "Now == "+item.getItemId(), Toast.LENGTH_SHORT).show();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.simple_tabs);
mAdapter = new TestFragmentAdapter(getSupportFragmentManager());
mPager = (ViewPager)findViewById(R.id.pager);
mPager.setAdapter(mAdapter);
mIndicator = (TabPageIndicator)findViewById(R.id.indicator);
mIndicator.setViewPager(mPager);
}
class TestFragmentAdapter extends FragmentPagerAdapter {
private int mCount = CONTENT.length;
public TestFragmentAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
return TestFragment.newInstance(String.valueOf(position));
}
#Override
public int getCount() {
return mCount;
}
#Override
public CharSequence getPageTitle(int position) {
return CONTENT[position];
}
}
}
i want to add a list view to page one for example this list but i cant write a list fragment for this code please tel me what i do
public static final String[] list = new String[]{"France", "London", "Sweden"};
what can I do ?
First of all you have to understand what is a Fragment and how to instantiate it and how to send to it data (you should look the guide dedicated to Fragments and the documentation for Fragments here).
Then you have to do 2 things :
Create your custom list fragment, I suggest you to look at the android documentation of ListFragment and create a class that inherits from ListFragment.
public class CustomListFragment extends ListFragment {
// your code here to add content
}
Modify your TestFragmentAdapter to instanciate your new CustomListFragment when you are in the first page (see example below)
public class TestFragmentAdapter
extends FragmentPagerAdapter
{
protected final Class[] CONTENT_CLASSES = new Class[] { CustomListFragment.class, TestFragment.class};
protected final String[] CONTENT_TITLES = new String[] { "List", "Test"};
public TabAdapter( FragmentManager manager, Activity context )
{
super( manager );
this.context = context;
}
#Override
public Fragment getItem( int i )
{
Class targetFragmentClass = CONTENT_CLASSES[i];
Bundle args = new Bundle();
// add your args here
Fragment targetFragment = Fragment.instantiate( context, targetFragmentClass.getName(), args );
return targetFragment;
}
#Override
public int getCount()
{
return CONTENT_CLASSES.length;
}
#Override
public CharSequence getPageTitle( int position )
{
return CONTENT_TITLES[i];
}
}