Android intent data return null - android

I am starter at Android and now I want to transfer data using intent from one activity to another.
First activity will collect datas and give it to second. but on second the data returns null. So have some errors on there. Here are my code.
public void previewStack(final Context context, final CreateStackNewActivity createStackNewActivity, final Stack stackDetails) {
Map<String, String> options = new HashMap<String, String>();
if(stackDetails.getStackId() != -1){
options.put("stack_id", String.valueOf(stackDetails.getStackId()));
}
int index = 1;
for(StackLineNew stackLine : stackDetails.getLines()){
options.put("title" + index, stackLine.getTitle());
options.put("line_type" + index, Integer.toString(stackLine.getLineType().intValue));
options.put("title" + index, stackLine.getTitle());
if (stackLine.getBody().indexOf("file:/") == -1 && stackLine.getBody().indexOf("content:") == -1) {
options.put("description" + index, stackLine.getBody());
if (stackLine.getLineId() != -1) {
options.put("line_id" + index, Integer.toString(stackLine.getLineId()));
}
}
index++;
}
Call<GenericAPIResponse> call = Hype4DAPI.previewStack(stackDetails.getName(), stackDetails.getCategory(), Integer.toString(stackDetails.getLines().size()), options, "");
call.enqueue(new Callback<GenericAPIResponse>() {
#Override
public void onResponse(Call<GenericAPIResponse> call, Response<GenericAPIResponse> response) {
if(response.isSuccessful()) {
GenericAPIResponse saveStackResponse = response.body();
System.out.println(saveStackResponse);
Toast.makeText(context, saveStackResponse.toString(), Toast.LENGTH_SHORT).show();
createStackNewActivity.saveInProgress = false;
createStackNewActivity.somethingHasChanged = false;
createStackNewActivity.updatePostButtonState();
Intent itnt = new Intent(createStackNewActivity, StackDetailsPage.class);
itnt.putExtra("stackId", stackDetails.getStackId());
itnt.putExtra("isPreview", "true");
itnt.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
createStackNewActivity.startActivity(itnt);
} else {
System.out.println(response.errorBody());
Toast.makeText(context, response.errorBody().toString(), Toast.LENGTH_SHORT).show();
}
}
#Override
public void onFailure(Call<GenericAPIResponse> call, Throwable t) {
t.printStackTrace();
}
});
}
And the code of second activity
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_stack_details);
final Intent intent = getIntent();
final String stackId;
if (intent != null) { //Null Checking
stackId = intent.getStringExtra("stackId");
isPreview = intent.getStringExtra("isPreview");
stackTitleStr = intent.getStringExtra("stackTitle");
saveLine = (HashMap<String, Object>)intent.getSerializableExtra("saveLine");
}
else{
stackId = null;
}
On second activity, I have all variables are null. isPreview, stackTitleStr, saveLine are all null.
So anyone please help me quickly.

first you should not create the intent in the onResponse callBack method but create a static method in your StackDetailsPage activity that return the intent it needs. With that, this activity "said" to the other ones whats it needs, and it avoid duplicate string extra keys. use this :
//in StackDetailsPage activity
public static Intent getIntent(Context context, String stackId, String...)
{
Intent intent = new Intent(context, StackDetailsPage.class);
intent.putExtra("stackId", stackId);
...
return intent;
}
and then in onResponse method do that :
startActivity(StackDetailsPage.getIntent(context,stackDetails.getStackId(), ...))

Related

Get intent value Using getIntent() in MVVM repository

I am giving the first steps in MVVM, I have a imbd app using retrofit.
At this moment I have a dynamic URL that change the list of movies by passing a different movie id
#GET("3/movie/{movie_id}}/similar?api_key="+api_key+"&language=en-US&page=1")
Call<Similar> getAllSimilarMovies(#Path("movie_id") int movieId);
I have a Repository where I am trying to get the Intent values but the .getIntent doesn't work, the Intent is in the recyclerview passing the ID of the movie clicked
public class DetailsMovieRepository {
private List<ResultSimilar> similarMoviesList;
private MutableLiveData<List<ResultSimilar>> mutableLiveData = new MutableLiveData<>();
public MutableLiveData<List<ResultSimilar>> getSimilarMutableliveData() {
MovieDataService movieDataService = RetrofitInstance.getRetrofitInstance();
Intent intent = getIntent(); // DONT WORK!
int movieId = intent.getIntExtra("movie_id",0);
Call<Similar> call = movieDataService.getAllSimilarMovies(movieId);
call.enqueue(new Callback<Similar>() {
#Override
public void onResponse(Call<Similar> call, Response<Similar> response) {
Similar similar = response.body();
if (similar != null && similar.getResults() != null) {
similarMoviesList = similar.getResults();
mutableLiveData.setValue(similarMoviesList);
}
}
#Override
public void onFailure(Call<Similar> call, Throwable t) {
Log.e("onFailed", " ******" + t.getMessage() + "*******");
}
});
return mutableLiveData;
}
}
The question is how can I get the value from the Intent save as a var and pass here
Call<Similar> call = movieDataService.getAllSimilarMovies(---MY INTENT VALUE---);
Starting Intent in Adapter
private SimilarViewHolder(#NonNull View itemView) {
super(itemView);
movieNameTv = itemView.findViewById(R.id.name_movie_tv);
movieRatingTv = itemView.findViewById(R.id.rating_movie_tv);
moviePosterIV = itemView.findViewById(R.id.movie_poster_iv);
movieDateTv = itemView.findViewById(R.id.date_movie_tv);
movieVotesTv = itemView.findViewById(R.id.votes_movie_tv);
movieOriginalTitleTv = itemView.findViewById(R.id.original_title_tv);
movieLanguageTv = itemView.findViewById(R.id.language_movie_tv);
itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int position = getAdapterPosition();
ResultSimilar selectedMovie = similarMoviesList.get(position);
Intent intent = new Intent(context, DetailsActivity.class);
Bundle bundle = new Bundle();
bundle.putInt("movie_id",selectedMovie.getId());
intent.putExtras(bundle);
context.startActivity(intent);
Log.e("ddddd" , "***" + selectedMovie.getId());
}});
}
}
Data service
public interface MovieDataService {
String api_key = "5bbf68dcf3b4ad3875ef7b2ed5ddfe1a";
#GET("3/movie/now_playing?api_key="+api_key+"&language=en-US&page=1")
Call<Movies> getAllMovies();
#GET("3/movie/{movie_id}}?api_key="+api_key+"&language=en-US")
Call<MovieResponse> getMovieDetails(#Path("movie_id") int movieId) ;
#GET("3/movie/{movie_id}}/similar?api_key="+api_key+"&language=en-US&page=1")
Call<Similar> getAllSimilarMovies(#Path("movie_id") int movieId);
}
Thank you!
If you want to get data from Intent then you should do it in your Activity class, then you can pass it to you repository from the constructor for example detailsMovieRepository(int id);

Service and interface

In my project i user Firebase Database. With it i read data frmo db the following way:
public void getSoftwareRecords() {
final List<Software> softwareList = new ArrayList<>();
databaseReference = firebaseDatabase.getReference("software");
getSoftwareRecordsListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot snapshot : dataSnapshot.getChildren()) {
softwareList.add(snapshot.getValue(Software.class));
}
Log.d(TAG, "Software from server count: " + softwareList.size());
onSoftwareTransactionListener.onSuccessSyncListOfSoftware(softwareList);
}
#Override
public void onCancelled(DatabaseError databaseError) {
Log.e(TAG, "Cant read software list from database: " + databaseError.getDetails());
// TODO describe error #102 for documentation
onSoftwareTransactionListener.onFailureSyncListOfSoftware("Ohh.");
}
};
databaseReference.addValueEventListener(getSoftwareRecordsListener);
After, this method i want to call in IntentService. As u notice, there is no return value = void. So, the question is how i can user service and interface together?
Service (as i wanted to use it):
public class ReadSoftwareListService extends IntentService implements Database.OnSoftwareTransactionListener {
private static final String TAG = ReadSoftwareListService.class.getSimpleName();
public static final String ACTION = "...";
public static final String RESULT_CODE = "RESULT_CODE";
public static final String RESULT_VALUE = "RESULT_VALUE";
private Intent in;
public ReadSoftwareListService() {
super("ReadSoftwareListService");
}
#Override
public void onCreate() {
super.onCreate();
}
#Override
protected void onHandleIntent(Intent intent) {
in = new Intent(ACTION);
Log.d(TAG, "ReadSoftwareListService:: onHandleIntent");
Database database = new Database(com.google.firebase.database.FirebaseDatabase.getInstance());
database.getSoftwareRecords(); // <- this is a method from code above.
}
#Override
public void onSuccessSyncListOfSoftware(List<Software> softwareList) {
Log.d(TAG, "ReadSoftwareListService:: onSuccessSyncListOfSoftware");
Bundle bundle = new Bundle();
bundle.putInt(RESULT_CODE, Activity.RESULT_OK);
in.putExtras(bundle);
// bundle.putSerializable(RESULT_VALUE, softwareList);
LocalBroadcastManager.getInstance(this).sendBroadcast(in);
}
#Override
public void onFailureSyncListOfSoftware(String message) {
Log.d(TAG, "ReadSoftwareListService:: onFailureSyncListOfSoftware");
Bundle bundle = new Bundle();
bundle.putInt(RESULT_CODE, Activity.RESULT_CANCELED);
bundle.putString(RESULT_VALUE, message);
in.putExtras(bundle);
LocalBroadcastManager.getInstance(this).sendBroadcast(in);
}
And reciever:
public final BroadcastReceiver softwareListReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
Log.d(TAG, "softwareListReceiver:: onReceive");
Bundle bundle = intent.getExtras();
int resultCode = bundle.getInt(RESULT_CODE);
if (resultCode == Activity.RESULT_OK) {
Log.d(TAG, "RESULT CODE == OK");
// softwareListAdapter.updateData(bundle.getParcelableArrayList(RESULT_VALUE));
} else {
Log.d(TAG, "RESULT CODE == CANCEL: " + bundle.getString(RESULT_VALUE));
}
}
};
If you really wanted to use IntentService here, you can go add ResultReceiver as a callback. Example:-
Intent intentService = new Intent(context, YourIntentService.class);
intentService.putExtra(StockService.REQUEST_RECEIVER_EXTRA, new ResultReceiver(null) {
#Override
protected void onReceiveResult(int resultCode, Bundle resultData) {
if (resultCode == StockService.RESULT_ID_QUOTE) {
...
}
}
});
startService(intentService);
Alternatively you can use Custom AsyncTask by passing interface as one of parameters.
Hope this helps.
Note: Vote up if you like this.

Restart activity from ActivityTestRule after failed test

I have modified ActivityTestRule to retry executing failed test cases. I need to restart the activity and re-run the execution whenever there is a test failure. I have tried calling mActivity.finish() but current activity is not finishing and not restarting. But the tests are restarted. I have followed this method from here
public class MyActivityTestRule<T extends Activity> extends ActivityTestRule<T> {
private final Class<T> mActivityClass;
private T mActivity;
private static final String TAG = "ActivityInstrumentationRule";
private boolean mInitialTouchMode = false;
private Instrumentation mInstrumentation;
public MyActivityTestRule(Class<T> activityClass, boolean initialTouchMode, boolean launchActivity) {
super(activityClass, initialTouchMode, launchActivity);
mActivityClass = activityClass;
mInitialTouchMode = initialTouchMode;
mInstrumentation = InstrumentationRegistry.getInstrumentation();
}
#Override
public Statement apply(Statement base, Description description) {
final String testClassName = description.getClassName();
final String testMethodName = description.getMethodName();
final Context context = InstrumentationRegistry.getTargetContext();
/* android.support.test.espresso.Espresso.setFailureHandler(new FailureHandler() {
#Override public void handle(Throwable throwable, Matcher<View> matcher) {
if(AutomationTestCase.mEnableScreenshotOnFailure)
SpoonScreenshotOnFailure.perform("espresso_assertion_failed", testClassName, testMethodName);
new DefaultFailureHandler(context).handle(throwable, matcher);
}
});*/
// return super.apply(base, description);
return statement(base, description);
}
private Statement statement(final Statement base, final Description description) {
return new Statement() {
#Override
public void evaluate() throws Throwable {
Throwable caughtThrowable = null;
//retry logic
for (int i = 0; i < 3; i++) {
try {
launchAppActivity(getActivityIntent());
base.evaluate();
return;
} catch (Throwable t) {
caughtThrowable = t;
System.err.println(description.getDisplayName() + ": run " + (i+1) + " failed");
finishActivity();
} finally {
finishActivity();
}
}
System.err.println(description.getDisplayName() + ": giving up after " + 3 + " failures");
throw caughtThrowable;
}
};
}
void finishActivity() {
if (mActivity != null) {
mActivity.finish();
mActivity = null;
}
}
public T launchAppActivity(#Nullable Intent startIntent) {
// set initial touch mode
mInstrumentation.setInTouchMode(mInitialTouchMode);
final String targetPackage = mInstrumentation.getTargetContext().getPackageName();
// inject custom intent, if provided
if (null == startIntent) {
startIntent = getActivityIntent();
if (null == startIntent) {
Log.w(TAG, "getActivityIntent() returned null using default: " +
"Intent(Intent.ACTION_MAIN)");
startIntent = new Intent(Intent.ACTION_MAIN);
}
}
startIntent.setClassName(targetPackage, mActivityClass.getName());
startIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
Log.d(TAG, String.format("Launching activity %s",
mActivityClass.getName()));
beforeActivityLaunched();
// The following cast is correct because the activity we're creating is of the same type as
// the one passed in
mActivity = mActivityClass.cast(mInstrumentation.startActivitySync(startIntent));
mInstrumentation.waitForIdleSync();
afterActivityLaunched();
return mActivity;
}}
If your test ended up in a different activity than what the ActivityTestRule was initialized as, you'll have to close all the activities in the backstack. This example may help:
https://gist.github.com/patrickhammond/19e584b90d7aae20f8f4

List ImageView repeating same image when shared

I have a listView that is supposed to accept a shared message and image where the image is placed within the ImageView. This feature works for just the first message, but once an image is shared, each message received after that initial one becomes a copy of that same image even though the blank image placeholder was already set, which is just a one pixel black png:
holder.sharedSpecial.setImageResource(R.drawable.image_share_empty_holder);
An example is below:
The green textbox is the recipient. They have recieved a shared image from the yellow textbox. The yellow textbox then simply sends a normal message and I have set another image as a placeholder for normal messages: holder.sharedSpecial.setImageResource(R.drawable.image_share_empty_holder);
The same previously shared image takes precedence. I have used notifyDataSetChanged() so as to allow for the updating the adapter so that it would recognize not to use the same image, but to no avail.
How can I reformulate this class so that the image shared is only displayed with the proper message and not copied into each subsequent message?
The ArrayAdapter class:
public class DiscussArrayAdapter extends ArrayAdapter<OneComment> {
class ViewHolder {
TextView countryName;
ImageView sharedSpecial;
LinearLayout wrapper;
}
private TextView countryName;
private ImageView sharedSpecial;
private MapView locationMap;
private GoogleMap map;
private List<OneComment> countries = new ArrayList<OneComment>();
private LinearLayout wrapper;
private JSONObject resultObject;
private JSONObject imageObject;
String getSharedSpecialURL = null;
String getSharedSpecialWithLocationURL = null;
String specialsActionURL = "http://" + Global.getIpAddress()
+ ":3000/getSharedSpecial/";
String specialsLocationActionURL = "http://" + Global.getIpAddress()
+ ":3000/getSharedSpecialWithLocation/";
String JSON = ".json";
#Override
public void add(OneComment object) {
countries.add(object);
super.add(object);
}
public DiscussArrayAdapter(Context context, int textViewResourceId) {
super(context, textViewResourceId);
}
public int getCount() {
return this.countries.size();
}
private OneComment comment = null;
public OneComment getItem(int index) {
return this.countries.get(index);
}
public View getView(int position, View convertView, ViewGroup parent) {
final ViewHolder holder;
View row = convertView;
if (row == null) {
LayoutInflater inflater = (LayoutInflater) this.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
row = inflater.inflate(R.layout.message_list_item, parent, false);
holder = new ViewHolder();
holder.wrapper = (LinearLayout) row.findViewById(R.id.wrapper);
holder.countryName = (TextView) row.findViewById(R.id.comment);
holder.sharedSpecial = (ImageView) row.findViewById(R.id.sharedSpecial);
// Store the ViewHolder as a tag.
row.setTag(holder);
} else {
holder = (ViewHolder) row.getTag();
}
Log.v("COMMENTING","Comment is " + countries.get(position).comment);
//OneComment comment = getItem(position);
holder.countryName.setText(countries.get(position).comment);
// Initiating Volley
final RequestQueue requestQueue = VolleySingleton.getsInstance().getRequestQueue();
// Check if message has campaign or campaign/location attached
if (countries.get(position).campaign_id == "0" && countries.get(position).location_id == "0") {
holder.sharedSpecial.setImageResource(R.drawable.image_share_empty_holder);
Log.v("TESTING", "It is working");
} else if (countries.get(position).campaign_id != "0" && countries.get(position).location_id != "0") {
// If both were shared
getSharedSpecialWithLocationURL = specialsLocationActionURL + countries.get(position).campaign_id + "/" + countries.get(position).location_id + JSON;
// Test Campaign id = 41
// Location id = 104
// GET JSON data and parse
JsonObjectRequest getCampaignLocationData = new JsonObjectRequest(Request.Method.GET, getSharedSpecialWithLocationURL, null,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
// Parse the JSON:
try {
resultObject = response.getJSONObject("shared");
} catch (JSONException e) {
e.printStackTrace();
}
// Get and set image
Picasso.with(getContext()).load("http://" + Global.getIpAddress() + ":3000" + adImageURL).into(holder.sharedSpecial);
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.d("Error.Response", error.toString());
}
}
);
requestQueue.add(getCampaignLocationData);
} else if (countries.get(position).campaign_id != "0" && countries.get(position).location_id == "0") {
// Just the campaign is shared
getSharedSpecialURL = specialsActionURL + countries.get(position).campaign_id + JSON;
// Test Campaign id = 41
// GET JSON data and parse
JsonObjectRequest getCampaignData = new JsonObjectRequest(Request.Method.GET, getSharedSpecialURL, null,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
// Parse the JSON:
try {
resultObject = response.getJSONObject("shared");
} catch (JSONException e) {
e.printStackTrace();
}
// Get and set image
Picasso.with(getContext()).load("http://" + Global.getIpAddress() + ":3000" + adImageURL).into(holder.sharedSpecial);
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.d("Error.Response", error.toString());
}
}
);
requestQueue.add(getCampaignData);
// Location set to empty
}
// If left is true, then yellow, if not then set to green bubble
holder.countryName.setBackgroundResource(countries.get(position).left ? R.drawable.bubble_yellow : R.drawable.bubble_green);
holder.wrapper.setGravity(countries.get(position).left ? Gravity.LEFT : Gravity.RIGHT);
return row;
}
}
The messaging class that sends normal messages only but can receive image messages and set to the adapter:
public class GroupMessaging extends Activity {
private static final int MESSAGE_CANNOT_BE_SENT = 0;
public String username;
public String groupname;
private Button sendMessageButton;
private Manager imService;
private InfoOfGroup group = new InfoOfGroup();
private InfoOfGroupMessage groupMsg = new InfoOfGroupMessage();
private StorageManipulater localstoragehandler;
private Cursor dbCursor;
private com.example.feastapp.ChatBoxUi.DiscussArrayAdapter adapter;
private ListView lv;
private EditText editText1;
private ServiceConnection mConnection = new ServiceConnection() {
public void onServiceConnected(ComponentName className, IBinder service) {
imService = ((MessagingService.IMBinder) service).getService();
}
public void onServiceDisconnected(ComponentName className) {
imService = null;
Toast.makeText(GroupMessaging.this, R.string.local_service_stopped,
Toast.LENGTH_SHORT).show();
}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.message_activity);
lv = (ListView) findViewById(R.id.listView1);
adapter = new DiscussArrayAdapter(getApplicationContext(), R.layout.message_list_item);
lv.setAdapter(adapter);
editText1 = (EditText) findViewById(R.id.editText1);
sendMessageButton = (Button) findViewById(R.id.sendMessageButton);
Bundle extras = this.getIntent().getExtras();
group.userName = extras.getString(InfoOfGroupMessage.FROM_USER);
group.groupName = extras.getString(InfoOfGroup.GROUPNAME);
group.groupId = extras.getString(InfoOfGroup.GROUPID);
String msg = extras.getString(InfoOfGroupMessage.GROUP_MESSAGE_TEXT);
setTitle("Group: " + group.groupName);
// Retrieve the information
localstoragehandler = new StorageManipulater(this);
dbCursor = localstoragehandler.groupGet(group.groupName);
if (dbCursor.getCount() > 0) {
// Probably where the magic happens, and keeps pulling the same
// thing
int noOfScorer = 0;
dbCursor.moveToFirst();
while ((!dbCursor.isAfterLast())
&& noOfScorer < dbCursor.getCount()) {
noOfScorer++;
}
}
localstoragehandler.close();
if (msg != null) {
// Then friends username and message, not equal to null, recieved
adapter.add(new OneComment(true, group.groupId + ": " + msg, "0", "0"));
adapter.notifyDataSetChanged();
((NotificationManager) getSystemService(NOTIFICATION_SERVICE))
.cancel((group.groupId + msg).hashCode());
}
// The send button
sendMessageButton.setOnClickListener(new OnClickListener() {
CharSequence message;
Handler handler = new Handler();
public void onClick(View arg0) {
message = editText1.getText();
if (message.length() > 0) {
// When general texting, the campaign and location will always be "0"
// Only through specials sharing is the user permitted to change the campaign and location to another value
adapter.add(new OneComment(false, imService.getUsername() + ": " + message.toString(), "0", "0"));
adapter.notifyDataSetChanged();
localstoragehandler.groupInsert(imService.getUsername(), group.groupName,
group.groupId, message.toString(), "0", "0");
// as msg sent, will blank out the text box so can write in
// again
editText1.setText("");
Thread thread = new Thread() {
public void run() {
try {
// JUST PUTTING "0" AS A PLACEHOLDER FOR CAMPAIGN AND LOCATION
// IN FUTURE WILL ACTUALLY ALLOW USER TO SHARE CAMPAIGNS
if (imService.sendGroupMessage(group.groupId,
group.groupName, message.toString(), "0", "0") == null) {
handler.post(new Runnable() {
public void run() {
Toast.makeText(
getApplicationContext(),
R.string.message_cannot_be_sent,
Toast.LENGTH_LONG).show();
// showDialog(MESSAGE_CANNOT_BE_SENT);
}
});
}
} catch (UnsupportedEncodingException e) {
Toast.makeText(getApplicationContext(),
R.string.message_cannot_be_sent,
Toast.LENGTH_LONG).show();
e.printStackTrace();
}
}
};
thread.start();
}
}
});
}
#Override
protected Dialog onCreateDialog(int id) {
int message = -1;
switch (id) {
case MESSAGE_CANNOT_BE_SENT:
message = R.string.message_cannot_be_sent;
break;
}
if (message == -1) {
return null;
} else {
return new AlertDialog.Builder(GroupMessaging.this)
.setMessage(message)
.setPositiveButton(R.string.OK,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int whichButton) {
/* User clicked OK so do some stuff */
}
}).create();
}
}
#Override
protected void onPause() {
super.onPause();
unregisterReceiver(groupMessageReceiver);
unbindService(mConnection);
ControllerOfGroup.setActiveGroup(null);
}
#Override
protected void onResume() {
super.onResume();
bindService(new Intent(GroupMessaging.this, MessagingService.class),
mConnection, Context.BIND_AUTO_CREATE);
IntentFilter i = new IntentFilter();
i.addAction(MessagingService.TAKE_GROUP_MESSAGE);
registerReceiver(groupMessageReceiver, i);
ControllerOfGroup.setActiveGroup(group.groupName);
}
// For receiving messages form other users...
public class GroupMessageReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
Bundle extra = intent.getExtras();
//Log.i("GroupMessaging Receiver ", "received group message");
String username = extra.getString(InfoOfGroupMessage.FROM_USER);
String groupRId = extra.getString(InfoOfGroupMessage.TO_GROUP_ID);
String message = extra
.getString(InfoOfGroupMessage.GROUP_MESSAGE_TEXT);
// NEED TO PLACE INTO THE MESSAGE VIEW!!
String received_campaign_id = extra.getString(InfoOfGroupMessage.CAMPAIGN_SHARED);
String received_location_id = extra.getString(InfoOfGroupMessage.LOCATION_SHARED);
// NEED TO INTEGRATE THIS INTO LOGIC ABOVE, SO IT MAKES SENSE
if (username != null && message != null) {
if (group.groupId.equals(groupRId)) {
adapter.add(new OneComment(true, username + ": " + message, received_campaign_id, received_location_id));
localstoragehandler
.groupInsert(username, groupname, groupRId, message, received_campaign_id, received_location_id);
Toast.makeText(getApplicationContext(), "received_campaign: " + received_campaign_id +
" received_location:" + received_location_id, Toast.LENGTH_LONG).show();
received_campaign_id = "0";
received_location_id = "0";
} else {
if (message.length() > 15) {
message = message.substring(0, 15);
}
Toast.makeText(GroupMessaging.this,
username + " says '" + message + "'",
Toast.LENGTH_SHORT).show();
}
}
}
}
;
// Build receiver object to accept messages
public GroupMessageReceiver groupMessageReceiver = new GroupMessageReceiver();
#Override
protected void onDestroy() {
super.onDestroy();
if (localstoragehandler != null) {
localstoragehandler.close();
}
if (dbCursor != null) {
dbCursor.close();
}
}
}
I have gone through your code and this is common problem with listview that images starts repeating itself. In your case I think you have assigned image to Imageview every if and else if condition but if none of the condition satisfy it uses the previous image.
I would suggest to debug the getview method and put break points on the setImageResource. I use volley for these image loading and it has a method called defaultImage so that if no url is there the image is going to get the default one. So add that default case and see if it works.
If any of the above point is not clear feel free to comment.

RESULT ERROR in In-app Billing for android

I am implementing Inapp billing for the products in my app for that i refered dungeons example and implementing from that!! But now i am not about to display checkout dialog box in my application and i even not getting any error in logcat..The application showing result as ERROR in a dialog box with NO CONNECTION MESSAGE IN IT
I am tracing the problem using logs.The code that i am using to display checkout dialog box is
In My Main Class::::::::::
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Intent j = getIntent();
int position = j.getExtras().getInt("BId");
System.err.println("Bid="+position);
Log.i("J","gf");
mHandler = new Handler();
mBooksPurchaseObserver = new BooksPurchaseObserver(mHandler);
mBillingService = new BillingService();
mBillingService.setContext(this);
mItemName = getString(CATALOG[position].nameId);
mSku = CATALOG[position].sku;
System.err.println("mSku_______="+mSku);
System.err.println("mItemName____="+mItemName);
System.err.println("Consts.DEBUG=="+Consts.DEBUG);
ResponseHandler.register(mBooksPurchaseObserver);
if (mBillingService.checkBillingSupported()) {
Log.i("ds","bsc_checkconnection");
}
if (Consts.DEBUG!=true) {
Log.d(TAG, "buying: " + mItemName + " sku: " + mSku);
Log.i("x","x");
}
mPurchaseDatabase = new PurchaseDatabase(this);
if(!mBillingService.requestPurchase(mItemName, mSku)){
Log.e("this is exp","request purchase______________");
showDialog(DIALOG_BILLING_NOT_SUPPORTED_ID);
}
setupWidgets();
Log.i("ga","Request purchaseeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee");
// Check if billing is supported.
Log.i("ga","Request purchaseeeeeeeeeee");
}
In Billing Service Class::::
class RequestPurchase extends BillingRequest {
public final String mProductId;
public final String mDeveloperPayload;
public RequestPurchase(String itemId) {
this(itemId, null);
Log.i("ga","Request purchase");
}
public RequestPurchase(String itemId, String developerPayload) {
// This object is never created as a side effect of starting this
// service so we pass -1 as the startId to indicate that we should
// not stop this service after executing this request.
super(-1);
System.err.println("itemId="+itemId);
Log.i("fads","request only");
mProductId = itemId;
mDeveloperPayload = developerPayload;
}
#Override
protected long run() throws RemoteException {
Log.i("gaaaaaaaaa","Request purchase");
Bundle request = makeRequestBundle("REQUEST_PURCHASE");
request.putString(Consts.BILLING_REQUEST_ITEM_ID, mProductId);
// Note that the developer payload is optional.
if (mDeveloperPayload != null) {
request.putString(Consts.BILLING_REQUEST_DEVELOPER_PAYLOAD, mDeveloperPayload);
}
System.err.println("mService===="+mService);
Bundle response = mService.sendBillingRequest(request);
System.err.println("response__"+response);
System.err.println("response__!!!!!!!!!!!!"+Consts.BILLING_RESPONSE_PURCHASE_INTENT);
PendingIntent pendingIntent
= response.getParcelable(Consts.BILLING_RESPONSE_PURCHASE_INTENT);
System.err.println("Pending Intent==="+pendingIntent);
Log.i("12","12");
if (pendingIntent == null) {
Log.e(TAG, "Error with requestPurchase");
return Consts.BILLING_RESPONSE_INVALID_REQUEST_ID;
}
Log.i("2","2");
Intent intent = new Intent();
Log.i("222222","11111");
System.err.println("Intent is equals to__"+intent);
System.err.println("pendingIntent is equals to__"+pendingIntent);
// System.err.printf("fsd",ResponseHandler.buyPageIntentResponse(pendingIntent, intent));
ResponseHandler.buyPageIntentResponse(pendingIntent, intent);
Log.i("f","fdas");
return response.getLong(Consts.BILLING_RESPONSE_REQUEST_ID,
Consts.BILLING_RESPONSE_INVALID_REQUEST_ID);
}
#Override
protected void responseCodeReceived(ResponseCode responseCode) {
Log.i("response code","response code");
ResponseHandler.responseCodeReceived(BillingService.this, this, responseCode);
}
}
My CheckbillingSupporting class
class CheckBillingSupported extends BillingRequest {
public CheckBillingSupported() {
// This object is never created as a side effect of starting this
// service so we pass -1 as the startId to indicate that we should
// not stop this service after executing this request.
super(-1);
}
#Override
protected long run() throws RemoteException {
Bundle request = makeRequestBundle("CHECK_BILLING_SUPPORTED");
Bundle response = mService.sendBillingRequest(request);
System.err.println("response code____"+Consts.BILLING_RESPONSE_RESPONSE_CODE);
int responseCode = response.containsKey(Consts.BILLING_RESPONSE_RESPONSE_CODE)
? response.getInt(Consts.BILLING_RESPONSE_RESPONSE_CODE)
: ResponseCode.RESULT_BILLING_UNAVAILABLE.ordinal();
if (Consts.DEBUG) {
Log.i(TAG, "CheckBillingSupported response code: " +
ResponseCode.valueOf(responseCode));
}
boolean billingSupported = (responseCode == ResponseCode.RESULT_OK.ordinal());
ResponseHandler.checkBillingSupportedResponse(billingSupported);
return Consts.BILLING_RESPONSE_INVALID_REQUEST_ID;
}
}
Could any one tell me were i went wrong?

Categories

Resources