Android - Client Server, Post Request - java

Situation :
I am working on Client-Server Communication.
When the users save the data (name of product, image, note), it should be transferred to the server side of the database.
But, I don't know how to code http Post request on the client side(Android).
MyWishlistsActivity.java
public class MyWishlistsActivity extends ListActivity {
SQLiteConnector sqlCon;
private CustomWishlistsAdapter custAdapter;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
String[] from = new String[] { Wishlists.NAME, Wishlists.NOTE };
int[] to = new int[] { R.id.name };
custAdapter = new CustomWishlistsAdapter(this,R.layout.wishlist_list_item, null, from, to);
this.setListAdapter(custAdapter);
}
#Override
protected void onResume() {
super.onResume();
new GetContacts().execute((Object[]) null);
}
#SuppressWarnings("deprecation")
#Override
protected void onStop() {
Cursor cursor = custAdapter.getCursor();
if (cursor != null)
cursor.deactivate();
custAdapter.changeCursor(null);
super.onStop();
}
private class GetContacts extends AsyncTask<Object, Object, Cursor> {
SQLiteConnector dbConnector = new SQLiteConnector(MyWishlistsActivity.this);
#Override
protected Cursor doInBackground(Object... params) {
return dbConnector.getAllWishlists();
}
#Override
protected void onPostExecute(Cursor result) {
custAdapter.changeCursor(result);
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
Intent addWishlists = new Intent(MyWishlistsActivity.this,AddEditWishlists.class);
startActivity(addWishlists);
//Client-Server
Intent addWishlists2 = new Intent(MyWishlistsActivity.this,Server_AddWishlists.class);
startActivity(addWishlists2);
//Client-Server End
return super.onOptionsItemSelected(item);
}
}
AddWishlists.java
public class AddEditWishlists extends Activity {
private EditText inputname;
private EditText inputnote;
private Button upload;
private Bitmap yourSelectedImage;
private ImageView inputphoto;
private Button save;
private int id;
private byte[] blob=null;
byte[] image=null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.add_wishlist);
setUpViews();
}
private void setUpViews() {
inputname = (EditText) findViewById(R.id.inputname);
inputnote = (EditText) findViewById(R.id.inputnote);
inputphoto = (ImageView) findViewById(R.id.inputphoto);
Bundle extras = getIntent().getExtras();
if (extras != null) {
id=extras.getInt("id");
inputname.setText(extras.getString("name"));
inputnote.setText(extras.getString("note"));
image = extras.getByteArray("blob");
if (image != null) {
if (image.length > 3) {
inputphoto.setImageBitmap(BitmapFactory.decodeByteArray(image,0,image.length));
}
}
}
upload = (Button) findViewById(R.id.upload);
upload.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("image/*");
startActivityForResult(intent, 0);
}
});
save = (Button) findViewById(R.id.save);
save.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (inputname.getText().length() != 0) {
AsyncTask<Object, Object, Object> saveContactTask = new AsyncTask<Object, Object, Object>() {
#Override
protected Object doInBackground(Object... params) {
saveContact();
return null;
}
#Override
protected void onPostExecute(Object result) {
finish();
}
};
saveContactTask.execute((Object[]) null);
} else {
AlertDialog.Builder alert = new AlertDialog.Builder(
AddEditWishlists.this);
alert.setTitle("Error In Save Wish List");
alert.setMessage("You need to Enter Name of the Product");
alert.setPositiveButton("OK", null);
alert.show();
}
}
});
}
private void saveContact() {
if(yourSelectedImage!=null){
ByteArrayOutputStream outStr = new ByteArrayOutputStream();
yourSelectedImage.compress(CompressFormat.JPEG, 100, outStr);
blob = outStr.toByteArray();
}
else{blob=image;}
SQLiteConnector sqlCon = new SQLiteConnector(this);
if (getIntent().getExtras() == null) {
sqlCon.insertWishlist(inputname.getText().toString(), inputnote.getText().toString(), blob);
}
else {
sqlCon.updateWishlist(id, inputname.getText().toString(), inputnote.getText().toString(),blob);
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode,Intent resultdata) {
super.onActivityResult(requestCode, resultCode, resultdata);
switch (requestCode) {
case 0:
if (resultCode == RESULT_OK) {
Uri selectedImage = resultdata.getData();
String[] filePathColumn = { MediaStore.Images.Media.DATA };
Cursor cursor = getContentResolver().query(selectedImage,
filePathColumn, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
String filePath = cursor.getString(columnIndex);
cursor.close();
// Convert file path into bitmap image using below line.
yourSelectedImage = BitmapFactory.decodeFile(filePath);
inputphoto.setImageBitmap(yourSelectedImage);
}
}
}
}
ViewWishlist.java
public class ViewWishlist extends Activity {
private TextView name;
private TextView note;
private ImageView photo;
private Button backBtn;
private byte[] image;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.view_wishlist);
setUpViews();
}
private void setUpViews() {
name = (TextView) findViewById(R.id.inputname);
note = (TextView) findViewById(R.id.inputnote);
photo = (ImageView) findViewById(R.id.inputphoto);
Bundle extras = getIntent().getExtras();
if (extras != null) {
name.setText(extras.getString("name"));
note.setText(extras.getString("note"));
image = extras.getByteArray("blob");
if (image != null) {
if (image.length > 3) {
photo.setImageBitmap(BitmapFactory.decodeByteArray(image,0,image.length));
}
}
}
backBtn=(Button)findViewById(R.id.back);
backBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
finish();
}
});
}
}
CustomWishlistsAdapter.java
public class CustomWishlistsAdapter extends SimpleCursorAdapter {
private int layout;
private ImageButton editBtn;
private ImageButton delBtn;
LayoutInflater inflator;
public CustomWishlistsAdapter(Context context, int layout, Cursor c,String[] from, int[] to) {
super(context, layout, c, from, to,0);
this.layout = layout;
inflator= LayoutInflater.from(context);
}
public View newView(Context context, Cursor cursor, ViewGroup parent) {
View v = inflator.inflate(layout, parent, false);
return v;
}
#Override
public void bindView(View v, final Context context, Cursor c) {
final int id = c.getInt(c.getColumnIndex(Wishlists.ID));
final String name = c.getString(c.getColumnIndex(Wishlists.NAME));
final String note = c.getString(c.getColumnIndex(Wishlists.NOTE));
final byte[] image = c.getBlob(c.getColumnIndex(Wishlists.IMAGE));
ImageView iv = (ImageView) v.findViewById(R.id.inputphoto);
if (image != null) {
if (image.length > 3) {
iv.setImageBitmap(BitmapFactory.decodeByteArray(image, 0,image.length));
}
}
TextView tname = (TextView) v.findViewById(R.id.name);
tname.setText(name);
final SQLiteConnector sqlCon = new SQLiteConnector(context);
editBtn=(ImageButton) v.findViewById(R.id.edit_btn);
editBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent=new Intent(context,AddEditWishlists.class).setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.putExtra("id", id);
intent.putExtra("name", name);
intent.putExtra("note", note);
intent.putExtra("blob", image);
context.startActivity(intent);
}
});
delBtn=(ImageButton) v.findViewById(R.id.del_btn);
delBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
sqlCon.deleteWishlist(id);
Intent intent=new Intent(context,MyWishlistsActivity.class).setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(intent);
}
});
v.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent=new Intent(context,ViewWishlist.class).setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.putExtra("id", id);
intent.putExtra("name", name);
intent.putExtra("note", note);
intent.putExtra("blob", image);
context.startActivity(intent);
}
});
}
}
This is my code.
Please help me how to add http post request on this code..
And also the php on the Server side .

For the Android HttpPost (to send JSON serialized data to a server)
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost("url_of_the_server");
JSONObject json = new JSONObject();
json.put("name", name);
json.put("note", note);
StringEntity se = new StringEntity(json.toString());
se.setContentType(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
post.setEntity(se);
HttpResponse response = client.execute(post);
//With response you can check the server return status code(to check if the request has been made correctly like so
StatusLine sLine = response.getStatusLine();
int statusCode = sLine.getStatusCode();
For more information on how to call a php web service there is a pretty nice tutorial that can be found here

Related

Cant get my API data to display on other pages

The code I've done was followed closely by a few YouTube tutorials. I'm designing an Age of Empires app that takes in the data from a public API. When the user progresses through the pages then different parts of the API data are shown. What I wanted it to do was get the data from the main activity (where the API is retrieved) and put some of its many data into the UniqueUnit page. It's using something called serializable which I can't quite understand how it works yet.
For the record, it works in getting the data from page 'DetailedCivilization' but just completely breaks on 'UniqueUnit'page.
MainActivity.java
package com.example.ageofempires2;
import ...
public class MainActivity extends AppCompatActivity {
public static final String TAG = "tag";
RecyclerView itemList;
Adapter adapter;
List<Civilizations> all_civilizations;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
getSupportActionBar().setTitle("Civilizations menu");
all_civilizations = new ArrayList<>();
itemList = findViewById(R.id.itemList);
itemList.setLayoutManager(new LinearLayoutManager(this));
adapter = new Adapter(this, all_civilizations);
itemList.setAdapter(adapter);
getJsonData();
}
private void getJsonData() {
String URL = "https://age-of-empires-2-api.herokuapp.com/api/v1/civilizations";
RequestQueue requestQueue = Volley.newRequestQueue(this);
JsonObjectRequest objectRequest = new JsonObjectRequest(Request.Method.GET, URL, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
JSONArray civilizations = response.getJSONArray("civilizations");
JSONObject civilizationsData = civilizations.getJSONObject(0);
Log.d(TAG, "onResponse "+ civilizationsData);
for (int i=0; i< civilizationsData.length();i++){
JSONObject civilization = civilizations.getJSONObject(i);
Civilizations v = new Civilizations();
v.setName(civilization.getString("name"));
v.setArmy_type(civilization.getString("army_type"));
v.setExpansion(civilization.getString("expansion"));
v.setCivilization_bonus(civilization.getString("civilization_bonus"));
v.setUnique_unit(civilization.getString("unique_unit"));
all_civilizations.add(v);
adapter.notifyDataSetChanged();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.d(TAG, "onErrorResponse" + error.getMessage());
}
});
requestQueue.add(objectRequest);
}
}
Adapter.java
package com.example.ageofempires2;
import ...
public class Adapter extends RecyclerView.Adapter<Adapter.ViewHolder> {
private List<Civilizations> allCivilizations;
private Context context;
public Adapter(Context ctx, List<Civilizations> civilizationsData){
this.allCivilizations = civilizationsData;
this.context = ctx;
}
#NonNull
#Override
public ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.civilization_view,parent,false);
return new ViewHolder(v);
}
#Override
public void onBindViewHolder(#NonNull ViewHolder holder, final int position) {
holder.titleName.setText(allCivilizations.get(position).getName());
holder.vv.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Bundle b = new Bundle();
b.putSerializable("civilizationsData", allCivilizations.get(position));
Intent i = new Intent(context, DetailedCivilization.class);
i.putExtras(b);
v.getContext().startActivity(i);
}
});
}
#Override
public int getItemCount() {
return allCivilizations.size();
}
public class ViewHolder extends RecyclerView.ViewHolder{
TextView titleName;
TextView expansionName;
View vv;
public ViewHolder(#NonNull View itemView) {
super(itemView);
titleName = itemView.findViewById(R.id.civilizationUniqueUnits);
expansionName = itemView.findViewById(R.id.civilizationUnitDescription);
vv = itemView;
}
}
}
Civilizations.java
package com.example.ageofempires2;
import java.io.Serializable;
public class Civilizations implements Serializable {
private String name;
private String expansion;
private String army_type;
private String civilization_bonus;
private String unique_unit;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getExpansion() {
return expansion;
}
public void setExpansion(String expansion) {
this.expansion = expansion;
}
public String getArmy_type() {
return army_type;
}
public void setArmy_type(String army_type) {
this.army_type = army_type;
}
public String getCivilization_bonus() {
return civilization_bonus;
}
public void setCivilization_bonus(String civilization_bonus) {this.civilization_bonus = civilization_bonus; }
public String getUnique_unit() {
return unique_unit;
}
public void setUnique_unit(String unique_unit) {this.unique_unit = unique_unit; }
}
UniqueUnits.java
package com.example.ageofempires2;
import ...
public class UniqueUnit extends AppCompatActivity {
public static final String TAG = "TAG";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_unique_unit);
getSupportActionBar().setTitle("Unique Unit");
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
Intent incomingIntent = getIntent();
Bundle incomingName = incomingIntent.getExtras();
Civilizations v = (Civilizations) incomingName.getSerializable("civilizationsData");
Log.d(TAG, "onCreate: IDK MAN IT SHOULD WORK??" +incomingName);
TextView unit = findViewById(R.id.civilizationUnitDescription);
unit.setText(v.getUnique_unit());
}
}
DetailedCivilization.java
package com.example.ageofempires2;
import ...
public class DetailedCivilization extends AppCompatActivity {
public static final String TAG = "TAG";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_detailed_civilization);
getSupportActionBar().setTitle("Detailed view");
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
Intent i = getIntent();
Bundle data = i.getExtras();
Civilizations v = (Civilizations) data.getSerializable("civilizationsData");
TextView type = findViewById(R.id.civilizationType);
type.setText(v.getArmy_type());
TextView title = findViewById(R.id.civilizationUniqueUnits);
title.setText(v.getName());
TextView expansions = findViewById(R.id.civilizationUnitDescription);
expansions.setText(v.getExpansion());
TextView bonus = findViewById(R.id.civilizationBonus);
bonus.setText(v.getCivilization_bonus());
Button changeActivityTech = findViewById(R.id.tech_button);
Button changeActivityUnit = findViewById(R.id.unit_button);
changeActivityTech.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
activityTech();
}
});
changeActivityUnit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
activityUnit();
}
});
}
private void activityTech(){
Intent intent = new Intent(this, UniqueTech.class);
startActivity(intent);
}
private void activityUnit(){
Intent intent = new Intent(this, UniqueUnit.class);
startActivity(intent);
}
#Override
public boolean onOptionsItemSelected(#NonNull MenuItem item) {
if(item.getItemId() == android.R.id.home){
onBackPressed();
}
return super.onOptionsItemSelected(item);
}
}
Solutions is
private void activityUnit(Civilizations civ){
Bundle b = new Bundle();
b.putSerializable("civilizationsData", civ)
Intent intent = new Intent(this, UniqueUnit.class);
intent.putExtras(b);
startActivity(intent);
}
In DetailedCivilization.java
Rename v from line Civilizations v = (Civilizations) incomingName.getSerializable("civilizationsData"); to civ or something more descriptive
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_detailed_civilization);
getSupportActionBar().setTitle("Detailed view");
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
Intent i = getIntent();
Bundle data = i.getExtras();
Civilizations civ = (Civilizations) data.getSerializable("civilizationsData");
TextView type = findViewById(R.id.civilizationType);
type.setText(v.getArmy_type());
TextView title = findViewById(R.id.civilizationUniqueUnits);
title.setText(v.getName());
TextView expansions = findViewById(R.id.civilizationUnitDescription);
expansions.setText(v.getExpansion());
TextView bonus = findViewById(R.id.civilizationBonus);
bonus.setText(v.getCivilization_bonus());
Button changeActivityTech = findViewById(R.id.tech_button);
Button changeActivityUnit = findViewById(R.id.unit_button);
changeActivityTech.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
activityTech();
}
});
changeActivityUnit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
activityUnit(civ);
}
});
}
And pass Civilizations when you call activityUnit function
Basically you forgot to pass Civilizations when you go from DetailedCivilization.java to UniqueUnits.java

showing error when passing data through intent from java class which implements Filterable

Here is my full java class code.
It is showing null pointer exception. I have also add logcat screen shot. I am trying to solve this problem, but no way.Please help me if possible.
public class AppAdapter extends RecyclerView.Adapter<AppAdapter.AppViewHolder> implements Filterable {
// Load Settings
private AppPreferences appPreferences;
// AppAdapter variables
private List<AppInfo> appList;
private List<AppInfo> appListSearch;
private Context context;
public AppAdapter(List<AppInfo> appList, Context context) {
this.appList = appList;
this.context = context;
this.appPreferences = SystemInfoManager.getAppPreferences();
}
#Override
public int getItemCount() {
return appList.size();
}
public void clear() {
appList.clear();
notifyDataSetChanged();
}
#Override
public void onBindViewHolder(AppViewHolder appViewHolder, int i) {
AppInfo appInfo = appList.get(i);
appViewHolder.vName.setText(appInfo.getName());
appViewHolder.vApk.setText(appInfo.getAPK());
appViewHolder.vIcon.setImageDrawable(appInfo.getIcon());
setButtonEvents(appViewHolder, appInfo);
}
private void setButtonEvents(AppViewHolder appViewHolder, final AppInfo appInfo) {
ButtonFlat appAbout = appViewHolder.vAbout;
ButtonFlat appShare = appViewHolder.vShare;
final ImageView appIcon = appViewHolder.vIcon;
final CardView cardView = appViewHolder.vCard;
appAbout.setBackgroundColor(Color.BLUE);
appShare.setBackgroundColor(Color.BLUE);
appAbout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Activity activity = (Activity) context;
Intent intent = new Intent(context, AppActivity.class);
intent.putExtra("app_name", appInfo.getName());
intent.putExtra("app_apk", appInfo.getAPK());
intent.putExtra("app_version", appInfo.getVersion());
intent.putExtra("app_source", appInfo.getSource());
intent.putExtra("app_data", appInfo.getData());
Bitmap bitmap = ((BitmapDrawable) appInfo.getIcon()).getBitmap();
intent.putExtra("app_icon", bitmap);
intent.putExtra("app_isSystem", appInfo.isSystem());
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
String transitionName = context.getResources().getString(R.string.transition_app_icon);
ActivityOptions transitionActivityOptions = ActivityOptions.makeSceneTransitionAnimation(activity, appIcon, transitionName);
context.startActivity(intent, transitionActivityOptions.toBundle());
} else {
context.startActivity(intent);
activity.overridePendingTransition(R.anim.slide_in_right, R.anim.fade_back);
}
}
});
appShare.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
UtilsApp.copyFile(appInfo);
Intent shareIntent = UtilsApp.getShareIntent(UtilsApp.getOutputFilename(appInfo));
context.startActivity(Intent.createChooser(shareIntent,
String.format(context.getResources().getString(R.string.send_to), appInfo.getName())));
}
});
cardView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Activity activity = (Activity) context;
Intent intent = new Intent(context, AppActivity.class);
intent.putExtra("app_name", appInfo.getName());
intent.putExtra("app_apk", appInfo.getAPK());
intent.putExtra("app_version", appInfo.getVersion());
intent.putExtra("app_source", appInfo.getSource());
intent.putExtra("app_data", appInfo.getData());
Bitmap bitmap = ((BitmapDrawable) appInfo.getIcon()).getBitmap();
intent.putExtra("app_icon", bitmap);
intent.putExtra("app_isSystem", appInfo.isSystem());
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
String transitionName = context.getResources().getString(R.string.transition_app_icon);
ActivityOptions transitionActivityOptions = ActivityOptions.makeSceneTransitionAnimation(activity, appIcon, transitionName);
context.startActivity(intent, transitionActivityOptions.toBundle());
} else {
context.startActivity(intent);
activity.overridePendingTransition(R.anim.slide_in_right, R.anim.fade_back);
}
}
});
}
public Filter getFilter() {
return new Filter() {
#Override
protected FilterResults performFiltering(CharSequence charSequence) {
final FilterResults oReturn = new FilterResults();
final List<AppInfo> results = new ArrayList<>();
if (appListSearch == null) {
appListSearch = appList;
}
if (charSequence != null) {
if (appListSearch != null && appListSearch.size() > 0) {
for (final AppInfo appInfo : appListSearch) {
if (appInfo.getName().toLowerCase().contains(charSequence.toString())) {
results.add(appInfo);
}
}
}
oReturn.values = results;
oReturn.count = results.size();
}
return oReturn;
}
#Override
protected void publishResults(CharSequence charSequence, FilterResults filterResults) {
if (filterResults.count > 0) {
InstalledAppsFragment.setResultsMessage(false);
} else {
InstalledAppsFragment.setResultsMessage(true);
}
appList = (ArrayList<AppInfo>) filterResults.values;
notifyDataSetChanged();
}
};
}
#Override
public AppViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
View appAdapterView = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.app_layout, viewGroup, false);
return new AppViewHolder(appAdapterView);
}
public static class AppViewHolder extends RecyclerView.ViewHolder {
protected TextView vName;
protected TextView vApk;
protected ImageView vIcon;
protected ButtonFlat vAbout;
protected ButtonFlat vShare;
protected CardView vCard;
public AppViewHolder(View v) {
super(v);
vName = (TextView) v.findViewById(R.id.txtName);
vApk = (TextView) v.findViewById(R.id.txtApk);
vIcon = (ImageView) v.findViewById(R.id.imgIcon);
vAbout = (ButtonFlat) v.findViewById(R.id.btnExtract);
vShare = (ButtonFlat) v.findViewById(R.id.btnShare);
vCard = (CardView) v.findViewById(R.id.app_card);
}
}
}
Here is the logcat message:
https://i.stack.imgur.com/vVOr7.jpg
Please give me some solution if possible.
I have used context.getBaseContext() but it also gave error.
Instead of parsing context to activity use getActiviy()
Intent intent = new Intent(getActivity(), AppActivity.class);
Try change this line
Instead
Intent intent = new Intent(context, AppActivity.class);
to
Intent intent = new Intent(YourActivityName.this, AppActivity.class);

Query SearchView Crash ( Trying to implement SearchView Action bar )

Everything works fine, except that when I try to search on my app, it crashes. The problem is in the method onQueryTextChange, please help me to fix it:
MainActivity
public class MainActivity extends AppCompatActivity implements AdapterView.OnItemClickListener, SearchView.OnQueryTextListener {
private PackageManager packageManager = null;
private List<ApplicationInfo> applist = null;
private ApplicationAdapter listadaptor = null;
private static final int REQUEST_CAMERA_PERMISSION = 200;
Button goSettings;
ListView listApps;
Context context;
Button go_AndroBooster,goPerms,lockAll,unlockAll,goLogs;
Intent i;
private AccountHeader headerResult = null;
private Drawer result = null;
private MiniDrawer miniResult = null;
private CrossfadeDrawerLayout crossfadeDrawerLayout = null;
MaterialProgressBar loadingBar;
ColorManager colorManager;
RelativeLayout mainLayout;
ArrayList<ApplicationInfo> items;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
context = MainActivity.this;
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
colorManager = new ColorManager(this);
setSupportActionBar(toolbar);
mainLayout = (RelativeLayout) findViewById(R.id.mainLayout);
packageManager = getPackageManager();
listApps = (ListView) findViewById(R.id.listApps);
go_AndroBooster = (Button) findViewById(R.id.go_booster);
goPerms = (Button) findViewById(R.id.goPerms);
lockAll = (Button) findViewById(R.id.lock_all);
unlockAll = (Button) findViewById(R.id.unlock_all);
loadingBar = (MaterialProgressBar) findViewById(R.id.loadingBar);
goLogs = (Button) findViewById(R.id.goLogs);
goSettings = (Button) findViewById(R.id.lockSettings);
listApps.setItemsCanFocus(true);
startLockService();
setSupportActionBar(toolbar);
//set the back arrow in the toolbar
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setHomeButtonEnabled(true);
getSupportActionBar().setTitle(R.string.app_name);
getSupportActionBar().setBackgroundDrawable(new ColorDrawable(Color.parseColor("#25517d")));
final IProfile profile2 = new ProfileDrawerItem().withIcon(R.drawable.user_icon);
// Create the AccountHeader
headerResult = new AccountHeaderBuilder()
.withActivity(this)
.withTranslucentStatusBar(false)
.withHeaderBackground(R.drawable.header)
.addProfiles(profile2)
.build();
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
result = new DrawerBuilder()
.withActivity(this)
.withToolbar(toolbar)
.withDrawerLayout(R.layout.crossfade_material_drawer)
.withHasStableIds(true)
.withDrawerWidthDp(72)
.withGenerateMiniDrawer(true)
.withAccountHeader(headerResult) //set the AccountHeader we created earlier for the header
.addDrawerItems(
new PrimaryDrawerItem().withName(R.string.Home).withIcon(R.drawable.homee).withIdentifier(1),
new PrimaryDrawerItem().withName(R.string.logs).withIcon(R.drawable.cleanapp).withIdentifier(2),
new PrimaryDrawerItem().withName(R.string.resetpass).withIcon(R.drawable.boost).withIdentifier(3),
new PrimaryDrawerItem().withName(R.string.language).withIcon(R.drawable.share).withIdentifier(4),
new PrimaryDrawerItem().withName(R.string.share).withIcon(R.drawable.rate).withIdentifier(6),
new PrimaryDrawerItem().withName(R.string.rate).withIcon(R.drawable.rate).withIdentifier(7)
// new DividerDrawerItem(),
// new SecondaryDrawerItem().withName(R.string.drawer_item_seventh).withIcon(FontAwesome.Icon.faw_github).withIdentifier(7).withSelectable(false)
) // add the items we want to use with our Drawer
.withSelectedItemByPosition(1)
.withOnDrawerItemClickListener(new Drawer.OnDrawerItemClickListener() {
#Override
public boolean onItemClick(View view, int position, IDrawerItem drawerItem) {
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
if (drawerItem.getIdentifier() == 1) {
// Toast.makeText(MainActivity.this,"2",Toast.LENGTH_LONG).show();
result.closeDrawer();
} else if (drawerItem.getIdentifier() == 2) {
i = new Intent(getApplicationContext(), LogsActivity.class);
startActivity(i);
result.closeDrawer();
} else if (drawerItem.getIdentifier() == 3) {
i = new Intent(getApplicationContext(), SetLockTypeActivity.class);
startActivity(i);
result.closeDrawer();
} else if (drawerItem.getIdentifier() == 4) {
LanguagesDialog languagesDialog = new LanguagesDialog();
languagesDialog.show(getFragmentManager(), "LanguagesDialogFragment");
} else if (drawerItem.getIdentifier() == 6) {
Intent sharingIntent = new Intent(Intent.ACTION_SEND);
sharingIntent.setType("text/plain");
sharingIntent.putExtra(android.content.Intent.EXTRA_TEXT, "http://play.google.com/store/apps/details?id="
+ getPackageName());
sharingIntent.putExtra(android.content.Intent.EXTRA_SUBJECT, "Subject");
startActivity(Intent.createChooser(sharingIntent, getResources().getText(R.string.shareusing)));
result.closeDrawer();
}else if (drawerItem.getIdentifier() == 7) {
Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("http://play.google.com/store/apps/details?id="
+ getPackageName()));
startActivity(browserIntent);
result.closeDrawer();
}
//
//
return false;
}
})
.withSavedInstance(savedInstanceState)
.withShowDrawerOnFirstLaunch(false)
.build();
//get out our drawerLyout
crossfadeDrawerLayout = (CrossfadeDrawerLayout) result.getDrawerLayout();
//define maxDrawerWidth
crossfadeDrawerLayout.setMaxWidthPx(DrawerUIUtils.getOptimalDrawerWidth(this));
//add second view (which is the miniDrawer)
MiniDrawer miniResult = result.getMiniDrawer();
//build the view for the MiniDrawer
View view = miniResult.build(this);
//set the background of the MiniDrawer as this would be transparent
view.setBackgroundColor(UIUtils.getThemeColorFromAttrOrRes(this, com.mikepenz.materialdrawer.R.attr.material_drawer_background, com.mikepenz.materialdrawer.R.color.material_drawer_background));
//we do not have the MiniDrawer view during CrossfadeDrawerLayout creation so we will add it here
crossfadeDrawerLayout.getSmallView().addView(view, ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
//define the crossfader to be used with the miniDrawer. This is required to be able to automatically toggle open / close
miniResult.withCrossFader(new ICrossfader() {
#Override
public void crossfade() {
boolean isFaded = isCrossfaded();
crossfadeDrawerLayout.crossfade(400);
//only close the drawer if we were already faded and want to close it now
if (isFaded) {
result.getDrawerLayout().closeDrawer(GravityCompat.START);
}
}
#Override
public boolean isCrossfaded() {
return crossfadeDrawerLayout.isCrossfaded();
}
});
//hook to the crossfade event
crossfadeDrawerLayout.withCrossfadeListener(new CrossfadeDrawerLayout.CrossfadeListener() {
#Override
public void onCrossfade(View containerView, float currentSlidePercentage, int slideOffset) {
Log.e("CrossfadeDrawerLayout", "crossfade: " + currentSlidePercentage + " - " + slideOffset);
}
});
final Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
startReqUsageStat();
}
}, 3000);
lockAll.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
ManageLockedApps.lockAllApps(context);
final Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
finish();
}
}, 2000);
}
});
unlockAll.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
ManageLockedApps.resetLockedApps(context);
final Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
finish();
}
}, 2000);
}
});
goPerms.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent i = new Intent(MainActivity.this, RequestPermission.class);
startActivity(i);
}
});
goLogs.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent i = new Intent(MainActivity.this, LogsActivity.class);
startActivity(i);
}
});
go_AndroBooster.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
startApplication("");
}
});
goSettings.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent i = new Intent(MainActivity.this, SettingsActivity.class);
startActivity(i);
finish();
}
});
applist = checkForLaunchIntent(packageManager.getInstalledApplications(PackageManager.GET_META_DATA));
listadaptor = new ApplicationAdapter(MainActivity.this,
R.layout.app_list_item, applist);
final Handler handler1 = new Handler();
handler1.postDelayed(new Runnable() {
#Override
public void run() {
new LoadApplications().execute();
}
}, 1500);
new Thread(new Runnable() {
#Override
public void run() {
if (ActivityCompat.checkSelfPermission(context, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(context, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE}, REQUEST_CAMERA_PERMISSION);
}
if (ActivityCompat.checkSelfPermission(context, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(context, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE}, REQUEST_CAMERA_PERMISSION);
}
}
}).start();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
final MenuItem item = menu.findItem(R.id.action_search);
final SearchView searchView = (SearchView) MenuItemCompat.getActionView(item);
searchView.setOnQueryTextListener(this);
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();
return super.onOptionsItemSelected(item);
}
private void startLockService() {
if (!isMyServiceRunning(LockService.class)){
context.startService(new Intent(context, LockService.class));
}
}
private void stopLockService() {
context.stopService(new Intent(context, LockService.class));
}
private void startReqUsageStat(){
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.LOLLIPOP) {
if (!checkUsageStatsPermission()){
Intent intent = new Intent(Settings.ACTION_USAGE_ACCESS_SETTINGS);
startActivity(intent);
Toast.makeText(context,getString(R.string.please_give_usage_Stats),Toast.LENGTH_LONG).show();
}
}
} public boolean checkUsageStatsPermission(){
final UsageStatsManager usageStatsManager = (UsageStatsManager) context.getSystemService(Context.USAGE_STATS_SERVICE);
final List<UsageStats> queryUsageStats = usageStatsManager.queryUsageStats(UsageStatsManager.INTERVAL_DAILY, 0, System.currentTimeMillis());
return !queryUsageStats.isEmpty();
}
public void startApplication(String packageName)
{
try
{
Intent intent = new Intent("android.intent.action.MAIN");
intent.addCategory("android.intent.category.LAUNCHER");
intent.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
List<ResolveInfo> resolveInfoList = getPackageManager().queryIntentActivities(intent, 0);
for(ResolveInfo info : resolveInfoList)
if(info.activityInfo.packageName.equalsIgnoreCase(packageName))
{
launchComponent(info.activityInfo.packageName, info.activityInfo.name);
return;
}
showInMarket(packageName);
}
catch (Exception e)
{
showInMarket(packageName);
}
}
public String getPattern() {
File file = new File("/data/data/com.project.applocker/files/pattern");
StringBuilder text = new StringBuilder();
try {
BufferedReader br = new BufferedReader(new FileReader(file));
String line;
while ((line = br.readLine()) != null) {
text.append(line);
}
br.close();
} catch (IOException e) {
Log.d("okuma hatası", "no 1");
}
return text.toString();
}
private void launchComponent(String packageName, String name)
{
Intent intent = new Intent("android.intent.action.MAIN");
intent.addCategory("android.intent.category.LAUNCHER");
intent.setComponent(new ComponentName(packageName, name));
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
}
private void showInMarket(String packageName)
{
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse("market://details?id=" + packageName));
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
}
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
final List<ApplicationInfo> appsList = context.getPackageManager().getInstalledApplications(0);
final ApplicationInfo data = appsList.get(i);
final SwitchCompat lockApp = (SwitchCompat) view.findViewById(R.id.lockApp);
lockApp.performClick();
}
private boolean isMyServiceRunning(Class<?> serviceClass) {
ActivityManager manager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
for (ActivityManager.RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) {
if (serviceClass.getName().equals(service.service.getClassName())) {
return true;
}
}
return false;
}
#Override
public boolean onQueryTextSubmit(String query) {
return false;
}
#Override
public boolean onQueryTextChange(String newText) {
ArrayList<ApplicationInfo> templist = new ArrayList<>();
for (ApplicationInfo temp : items){
if (temp.toString().contains(newText.toLowerCase())){
templist.add(temp);
}
ArrayAdapter<ApplicationInfo> adapter = new ArrayAdapter<>(MainActivity.this, android.R.layout.simple_list_item_1,applist);
listApps.setAdapter(adapter);
return true;
}
return true;
};
private class LoadApplications extends AsyncTask<Void, Void, Void> {
#Override
protected Void doInBackground(Void... params) {
applist = checkForLaunchIntent(packageManager.getInstalledApplications(PackageManager.GET_META_DATA));
listadaptor = new ApplicationAdapter(MainActivity.this,
R.layout.app_list_item, applist);
if(!isMyServiceRunning(LockService.class)){
startLockService();
}
return null;
}
#Override
protected void onCancelled() {
super.onCancelled();
}
#Override
protected void onPostExecute(Void result) {
listApps.setAdapter(listadaptor);
listApps.setOnItemClickListener(MainActivity.this);
loadingBar.setVisibility(View.INVISIBLE);
super.onPostExecute(result);
}
#Override
protected void onPreExecute() {
loadingBar.setVisibility(View.VISIBLE);
super.onPreExecute();
}
#Override
protected void onProgressUpdate(Void... values) {
super.onProgressUpdate(values);
}
}
String[] alphabet = "abcdefghijklmnopqrstuvwxyz".split("");
#Override
public void onPause() {
super.onPause();
}
#Override
public void onResume() {
super.onResume();
}
#Override
public void onDestroy() {
super.onDestroy();
startLockService();
}
private List<ApplicationInfo> checkForLaunchIntent(List<ApplicationInfo> list) {
ArrayList<ApplicationInfo> applist = new ArrayList<ApplicationInfo>();
for (ApplicationInfo info : list) {
try {
if (!info.packageName.equals("com.google.android.googlequicksearchbox")) {
if (!info.packageName.equals("com.project.applocker")) {
if (!info.packageName.contains("launcher3")) {
if (!info.packageName.contains("launcher")) {//com.google.android.googlequicksearchbox
if (!info.packageName.contains("trebuchet")) {
if (null != packageManager.getLaunchIntentForPackage(info.packageName)) {
applist.add(info);
}
}
}
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
return applist;
}
}
Adapter
public class ApplicationAdapter extends ArrayAdapter<ApplicationInfo>{
private List<ApplicationInfo> appsList = null;
private Context context;
private PackageManager packageManager;
List<String> allAppList = null;
List<String> lockedAppList = null;
ColorManager colorManager;
SharedPreferences preferences;
SharedPreferences.Editor editor;
public ApplicationAdapter(Context context, int textViewResourceId,
List<ApplicationInfo> appList) {
super(context, textViewResourceId, appList);
this.context = context;
allAppList = new ArrayList<String>();
colorManager = new ColorManager(context);
lockedAppList = new ArrayList<String>();
this.appsList = appList;
packageManager = context.getPackageManager();
preferences=context.getSharedPreferences("chosen_apps", context.MODE_PRIVATE);
Collections.sort(appsList, new ApplicationInfo.DisplayNameComparator(packageManager));
editor = preferences.edit();
}
#Override
public int getCount() {
return ((null != appsList) ? appsList.size() : 0);
}
#Override
public ApplicationInfo getItem(int position) {
return ((null != appsList) ? appsList.get(position) : null);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, final View convertView, ViewGroup parent) {
View view = convertView;
if (null == view) {
LayoutInflater layoutInflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = layoutInflater.inflate(R.layout.app_list_item, null);
}
final ApplicationInfo data = appsList.get(position);
if (null != data) {
ImageView iconview = (ImageView) view.findViewById(R.id.app_icon);
CardView cardViewApps = (CardView) view.findViewById(R.id.cardViewApps);
final SwitchCompat lockApp = (SwitchCompat) view.findViewById(R.id.lockApp);
lockApp.setText(data.loadLabel(packageManager));
iconview.setImageDrawable(data.loadIcon(packageManager));
if(preferences.getBoolean(data.packageName,false)){
lockApp.setChecked(true);
}
else{
lockApp.setChecked(false);
}
lockApp.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
context.stopService(new Intent(context, LockService.class));
if (lockApp.isChecked()){
Log.d("tıklanmış",""+data.packageName);
editor.putBoolean(data.packageName,true).apply();
}
if (!lockApp.isChecked()){
Log.d("silinmiş",""+data.packageName);
editor.putBoolean(data.packageName,false).apply();
}
context.startService(new Intent(context, LockService.class));
}
});
}
return view;
}
private void startLockService() {
context.startService(new Intent(context, LockService.class));
}
private void stopLockService() {
context.stopService(new Intent(context, LockService.class));
}
}
The problem is here:
#Override
public boolean onQueryTextChange(String newText) {
ArrayList<ApplicationInfo> templist = new ArrayList<>();
for (ApplicationInfo temp : items){
if (temp.toString().contains(newText.toLowerCase())){
templist.add(temp);
}
ArrayAdapter<ApplicationInfo> adapter = new ArrayAdapter<>(MainActivity.this, android.R.layout.simple_list_item_1,applist);
listApps.setAdapter(adapter);
return true;
}
return true;
};
I think your method should be like below
#Override
public boolean onQueryTextChange(String newText) {
ArrayList<ApplicationInfo> templist = new ArrayList<>();
for (ApplicationInfo temp : items){
if (temp.toString().contains(newText.toLowerCase())){
templist.add(temp);
}
}
if(templist != null && templist.size() > 0){}
ArrayAdapter<ApplicationInfo> adapter = new ArrayAdapter<>(MainActivity.this, android.R.layout.simple_list_item_1,templist);
listApps.setAdapter(adapter);
}else{
listApps.setAdapter(null);
}
return true;
};

Im about to refresh the current viewed Fragment from searching an item from API

In my application I am about to refresh the current viewed fragment after searching an item from API. My search bar is coming from Fragment activity and, when the result is there, it will be viewed in the second fragment, but the problem is, when I click search, it will reset into the 1st fragment.
Here's my code:
private ViewPager mPager;
private MyPagerAdapter mAdapter;
ImageView settings_btn;
EditText search;
//EditText search;
ImageView community_icon;
ImageView loyalty_icon;
ImageView tokens_icon;
Context context;
public CustomerAccount customerAccount;
private MyPagerAdapter pagerAdapter;
String offer = "cheese";
ProgressDialog progressDialog;
CustomListAdapterMerchant adapter;
String searchname;
ArrayList<RowItemMerchant> rowItem;
JSONObject offerlist;
int i;
JSONObject merchantList;
RowItemMerchant items;
ListView listView;
Bundle extras;
String empty;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_dashboard);
getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN);
if(savedInstanceState != null){
search.setText(savedInstanceState.getString("Key"));
}
search = (EditText) findViewById(R.id.searchView);
search.setOnEditorActionListener(new TextView.OnEditorActionListener() {
#Override
public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
if (actionId == EditorInfo.IME_ACTION_SEARCH) {
ConstantSearch.SEARCHNAME = search.getText().toString();
Intent intent = getIntent();
intent.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
intent.putExtra("IPUTTEDMERCHANT", ConstantSearch.SEARCHNAME);
finish();
startActivity(intent);
Log.d("SearchName",ConstantSearch.SEARCHNAME);
return true;
}
return false;
}
});
search.setOnKeyListener(new View.OnKeyListener() {
#Override
public boolean onKey(View v, int keyCode, KeyEvent event) {
// You can identify which key pressed buy checking keyCode value
// with KeyEvent.KEYCODE_
if (keyCode == KeyEvent.KEYCODE_DEL) {
ConstantSearch.SEARCHNAME = "";
Intent intent = getIntent();
intent.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
intent.putExtra("IPUTTEDMERCHANT", ConstantSearch.SEARCHNAME);
finish();
startActivity(intent);
Log.e("IME_TEST", "DEL KEY");
}
return false;
}
});
Intent intent = getIntent();
Bundle bd = intent.getExtras();
if(bd != null) {
String getName = (String) bd.get("IPUTTEDMERCHANT");
search.setText(getName);
}
LocationManager mlocManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
boolean enabled = mlocManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
if(!enabled) {
showDialogGPS();
}
mAdapter = new MyPagerAdapter(getSupportFragmentManager());
mPager = (ViewPager) findViewById(R.id.view_pager);
mPager.setAdapter(mAdapter);
final TextView ref1= (TextView) findViewById(R.id.ref1);
final TextView ref2= (TextView) findViewById(R.id.ref2);
final TextView ref3= (TextView) findViewById(R.id.ref);
final ImageView Image1 = (ImageView) findViewById(R.id.image1);
final ImageView Image2 = (ImageView) findViewById(R.id.image2);
final ImageView Image3 = (ImageView) findViewById(R.id.image3);
settings_btn = (ImageView) findViewById(R.id.settings_button);
settings_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent settings = new Intent(DashboardActivity.this, SettingsPromotion.class);
startActivity(settings);
}
});
ref1.setTextColor(ContextCompat.getColor(this, R.color.orange));
Image1.setImageResource(R.drawable.ic_community_on);
ref2.setTextColor(ContextCompat.getColor(this, R.color.blackColor));
Image2.setImageResource(R.drawable.ic_loyalty_off);
ref3.setTextColor(ContextCompat.getColor(this, R.color.blackColor));
Image3.setImageResource(R.drawable.ic_tokens_off);
ref1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mPager.setCurrentItem(0);
setToDefault();
ref1.setTextColor(ContextCompat.getColor(DashboardActivity.this, R.color.orange));
Image1.setImageResource(R.drawable.ic_community_on);
}
});
loyalty.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mPager.setCurrentItem(1);
setToDefault();
ref2.setTextColor(ContextCompat.getColor(DashboardActivity.this, R.color.orange));
Image2.setImageResource(R.drawable.ic_loyalty_on);
}
});
tokens.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mPager.setCurrentItem(2);
setToDefault();
ref3.setTextColor(ContextCompat.getColor(DashboardActivity.this, R.color.orange));
Image3.setImageResource(R.drawable.ic_tokens_on);
}
});
}
public void onSaveInstanceState(Bundle savedInstanceState) {
super.onSaveInstanceState(savedInstanceState);{
String savedText = search.getText().toString();
savedInstanceState.putString("Key", savedText);
}
}
private void showDialogGPS() {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setCancelable(false);
builder.setTitle("Allow \"My App\" to access you location while you use tha app?");
builder.setMessage("My App uses this to help customers find places. connect with merchants and more");
builder.setInverseBackgroundForced(true);
builder.setPositiveButton("Enable", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
startActivity(
new Intent(android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS));
}
});
builder.setNegativeButton("Ignore", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
AlertDialog alert = builder.create();
alert.show();
}
public void setToDefault()
{
TextView ref1 = (TextView) findViewById(R.id.ref1);
TextView ref2 = (TextView) findViewById(R.id.ref2);
TextView ref3 = (TextView) findViewById(R.id.ref3);
ImageView Image1 = (ImageView) findViewById(R.id.image1);
ImageView Image2 = (ImageView) findViewById(R.id.image2);
ImageView Image3 = (ImageView) findViewById(R.id.image3);
ref1.setTextColor(ContextCompat.getColor(this, R.color.blackColor));
Image1.setImageResource(R.drawable.ic_community_off);
ref2.setTextColor(ContextCompat.getColor(this, R.color.blackColor));
Image2.setImageResource(R.drawable.ic_loyalty_off);
ref3.setTextColor(ContextCompat.getColor(this, R.color.blackColor));
Image3.setImageResource(R.drawable.ic_tokens_off);
}
public static class MyPagerAdapter extends FragmentPagerAdapter
{
private static final int NUM_ITEMS = 3;
private Map<Integer, String> mFragmentTags;
private FragmentManager mFragmentManager;
private FragmentOne fragmentOne;
private FragmentTwo fragmentTwo;
private FragmentThree fragmentThree;
public MyPagerAdapter(FragmentManager fm)
{
super(fm);
mFragmentTags = new HashMap<Integer, String>();
fragmentOne = new FragmentOne();
fragmentTwo = new FragmentTwo();
fragmentThree = new FragmentThree();
}
#Override
public int getCount()
{
return NUM_ITEMS;
}
#Override
public Fragment getItem(int position)
{
if (position == 0)
{
return fragmentOne;
}
else if (position == 1)
{
return fragmentTwo;
}
else if (position == 2)
{
return fragmentThree;
}
else
{
Log.e("AuthActivity", "ViewPager invalid position");
return null;
}
}
}

How to pass data from activity to another activity on Android

I want to pass data from my Login Page to My Detail Page. However the Detail Page cannot accept the data because the String sent in Login Page has null value on Detail Page.
This is my Login Page Code:
public class MainActivity extends AppCompatActivity {
EditText editText, editText1;
Button button;
int success = 0;
ProgressDialog progressDialog;
JSONObject jsonObject;
HTTPURLConnection service;
String strname ="", strpass="";
String response;
String path = "http://sumbanggagasan.890m.com/select2.php";
Intent intent;
DetailGagasanku detailGagasanku;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
editText = (EditText) findViewById(R.id.nik);
editText1 = (EditText) findViewById(R.id.pass);
button = (Button) findViewById(R.id.signin);
service = new HTTPURLConnection();
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (!editText.getText().toString().equals("") && !editText1.getText().toString().equals("")){
strname = editText.getText().toString();
strpass = editText1.getText().toString();
response = null;
new PostDataTOServer().execute();
} else{
Toast.makeText(getApplicationContext(), "Please Enter all fields", Toast.LENGTH_LONG).show();
}
}
});
}
private class PostDataTOServer extends AsyncTask<Void, Void, Void> {
//Create hashmap Object to send parameters to web service
HashMap<String, String> postDataParams;
#Override
protected void onPreExecute() {
super.onPreExecute();
progressDialog = new ProgressDialog(MainActivity.this);
progressDialog.setMessage("Please wait...");
progressDialog.setCancelable(false);
progressDialog.show();
}
#Override
protected Void doInBackground(Void... arg0) {
postDataParams=new HashMap<String, String>();
postDataParams.put("NIK", strname);
postDataParams.put("pass", strpass);
//Call ServerData() method to call webservice and store result in response
response= service.ServerData(path,postDataParams);
try {
System.out.println(response + "menu");
jsonObject = new JSONObject(response);
//Get Values from JSONobject
System.out.println("success=" + jsonObject.get("successs"));
//success = jsonObject.getInt("success");
success = Integer.parseInt(jsonObject.getString("successs").trim());
System.out.println("Do in");
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
System.out.println("Post 1");
System.out.println(strname);
if (progressDialog.isShowing()) {
System.out.println("Post 2");
System.out.println(strpass);
progressDialog.dismiss();
}
if(success==1) {
//Toast.makeText(getApplicationContext(), "Berhasil", Toast.LENGTH_LONG).show();
Intent intent;
Bundle b;
b = new Bundle();
b.putString("username", strname);
intent = new Intent(getApplicationContext(), LandingPage.class);
intent.putExtras(b);
startActivity(intent);
} else{
Toast.makeText(getApplicationContext(), "Login gagal", Toast.LENGTH_LONG).show();
}
}
}
And this is my Details code:
public class DetailGagasanku extends AppCompatActivity {
TextView judul, manfaat;
Bundle bundle;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_detail_gagasanku);
judul = (TextView)findViewById(R.id.textJudul);
manfaat = (TextView) findViewById(R.id.textManfaat);
bundle = getIntent().getExtras();
judul.setText(bundle.getString("judul_gagasan"));
if (bundle != null) {
if(bundle.containsKey("username"))
{
String s = bundle.getString("username");
manfaat.setText(s);
}
else
{
System.out.println("not send");
}
}
}
}
I want to ask why that username has null value. For your information, that "judul_gagasan" variable can receive value from another activity. I send it from My Adapter.
this is my Adapter code:
public class GagasanAdapter extends RecyclerView.Adapter<GagasanAdapter.GagasanHolder> {
List<String> gagasanList = new ArrayList<>();
public GagasanAdapter(List<String> gagasanList) {
this.gagasanList = gagasanList;
Log.v("gagasanSize", "" + gagasanList.size());
}
#Override
public GagasanHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_gagasan, parent, false);
return new GagasanHolder(v);
}
#Override
public void onBindViewHolder(final GagasanHolder holder, final int position) {
Log.v("Gagasan[" + position + "]", gagasanList.get(position));
String item = gagasanList.get(position);
holder.judulGagasan.setText(item);
holder.judulGagasan.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Context context = v.getContext();
Intent intent = new Intent(context, DetailGagasanku.class);
intent.putExtra("judul_gagasan", holder.judulGagasan.getText().toString());
context.startActivity(intent);
}
});
}
#Override
public int getItemCount() {
return gagasanList.size();
}
public class GagasanHolder extends RecyclerView.ViewHolder{
TextView judulGagasan;
public GagasanHolder(View itemView) {
super(itemView);
judulGagasan = (TextView) itemView.findViewById(R.id.tvListGagasan);
}
}
}
You pass "username" in Bundle to LandingPage Activity, so you can't access in DetailGagasanku Activity.
So to access "username" in DetailGagasanku Activity, pass username from adapter.

Categories