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.
Related
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
I am using Volley for my data. I have an edit profile part of a fragment, its side is the main profile. I can successfully update my profile but when I Slide through my main profile the old data is still there. What should I put to update the mainprofile side of the fragment?
Here is MainProfile fragment I have MainProfileFragment
Here is its code:
public class MainProfileFragment extends Fragment{
private static final String TAG = "MainProfileFragment";
SessionManager sessionManager;
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_mainprofile, container, false);
return view;
}
#NonNull
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
sessionManager = new SessionManager(getActivity());
TextView name = (TextView) getView().findViewById(R.id.name);
TextView phoneNumber = (TextView) getView().findViewById(R.id.number);
TextView gender = (TextView) getView().findViewById(R.id.gender);
TextView address = (TextView) getView().findViewById(R.id.address);
TextView occupation = (TextView) getView().findViewById(R.id.occupation);
TextView birthDate = (TextView) getView().findViewById(R.id.birthDate);
TextView userType = (TextView) getView().findViewById(R.id.userType);
TextView id = (TextView) getView().findViewById(R.id.userID);
Button logout = (Button) getView().findViewById(R.id.logoutBtn);
HashMap<String, String> user = sessionManager.getUserDetail();
String mName = user.get(sessionManager.NAME);
String mNumber = user.get(sessionManager.NUMBER);
String mGender = user.get(sessionManager.GENDER);
String mAddress = user.get(sessionManager.ADDRESS);
String mOccupation = user.get(sessionManager.OCCUPATION);
String mBirthDate = user.get(sessionManager.BIRTHDATE);
String mUserType = user.get(sessionManager.USERTYPE);
String mUserID = user.get(sessionManager.ID);
id.setText(mUserID);
name.setText(mName);
phoneNumber.setText(mNumber);
gender.setText(mGender);
address.setText(mAddress);
occupation.setText(mOccupation);
birthDate.setText(mBirthDate);
userType.setText(mUserType);
logout.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
Intent intent = new Intent(getActivity(), LogoutEffect.class);
sessionManager.logout();
startActivity(intent);
}
});
}
}
Now beside it is the SideProfileFragment, it edits the profile data. Here is its code:
public class SideProfileFragment extends Fragment{
private static final String TAG = SideProfileFragment.class.getSimpleName();
private EditText name, birthDate, address, occupation, gender, number;
private Button btnSave;
SessionManager sessionManager;
String getId = "";
private static final String URL_READ = "http://isalonbyageeks.000webhostapp.com/readDetail.php";
private static final String URL_EDIT = "http://isalonbyageeks.000webhostapp.com/editDetail.php";
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_sideprofile, container, false);
return view;
}
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
sessionManager = new SessionManager(getActivity());
name = (EditText) getView().findViewById(R.id.userName);
birthDate = (EditText) getView().findViewById(R.id.userBirthDate);
address = (EditText) getView().findViewById(R.id.userAddress);
occupation = (EditText) getView().findViewById(R.id.userOccupation);
gender = (EditText) getView().findViewById(R.id.userGender);
number = (EditText) getView().findViewById(R.id.userNumber);
btnSave = (Button) getView().findViewById(R.id.buttonSaveEdit);
HashMap<String, String> user = sessionManager.getUserDetail();
getId = user.get(sessionManager.ID);
btnSave.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
SaveEditProfile();
}
});
}
private void getUserDetail(){
final ProgressDialog progressDialog = new ProgressDialog(getActivity());
progressDialog.setMessage("Loading...");
progressDialog.show();
StringRequest stringRequest = new StringRequest(Request.Method.POST, URL_READ,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
progressDialog.dismiss();
Log.i(TAG, response);
try {
JSONObject jsonObject = new JSONObject(response);
String success = jsonObject.getString("success");
JSONArray jsonArray = jsonObject.getJSONArray("read");
if(success.equals("1")){
for(int i = 0; i < jsonArray.length();i++){
JSONObject object = jsonArray.getJSONObject(i);
String strName = object.getString ("name");
String strNumber = object.getString("phone_number");
String strGender = object.getString("gender");
String strAddress = object.getString("address");
String strOccupation = object.getString("occupation");
String strBirthDate = object.getString("birth_date");
name.setText(strName);
birthDate.setText(strBirthDate);
address.setText(strAddress);
number.setText(strNumber);
gender.setText(strGender);
occupation.setText(strOccupation);
}
}
} catch (JSONException e) {
e.printStackTrace();
progressDialog.dismiss();
Toast.makeText(getActivity(),"Error Reading Detail" +e.toString(), Toast.LENGTH_LONG).show();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
progressDialog.dismiss();
}
})
{
#Override
protected Map<String, String> getParams() throws AuthFailureError{
Map<String, String> params = new HashMap<>();
params.put("id", getId);
return params;
}
};
RequestQueue requestQueue = Volley.newRequestQueue(getActivity());
requestQueue.add(stringRequest);
}
#Override
public void onResume(){
super.onResume();
getUserDetail();
}
private void SaveEditProfile(){
final String name = this.name.getText().toString().trim();
final String birthdate = this.birthDate.getText().toString().trim();
final String address = this.address.getText().toString().trim();
final String number = this.number.getText().toString().trim();
final String gender = this.gender.getText().toString().trim();
final String occupation = this.occupation.getText().toString().trim();
final String id = getId;
final String userType = sessionManager.USERTYPE;
final ProgressDialog progressDialog = new ProgressDialog(getActivity());
progressDialog.setMessage("Saving Details...");
progressDialog.show();
StringRequest stringRequest = new StringRequest(Request.Method.POST, URL_EDIT,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
progressDialog.dismiss();
try {
JSONObject jsonObject = new JSONObject(response);
String success = jsonObject.getString("success");
if(success.equals("1")){
Toast.makeText(getActivity(), "Edit Saved!", Toast.LENGTH_SHORT).show();
sessionManager.createSession(id, name, number, gender, address, occupation, birthdate,userType);
}
} catch (JSONException e) {
e.printStackTrace();
progressDialog.dismiss();
Toast.makeText(getActivity(), "Error"+e.toString(), Toast.LENGTH_SHORT).show();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
progressDialog.dismiss();
Toast.makeText(getActivity(), "Error "+ error.toString(), Toast.LENGTH_SHORT).show();
}
})
{
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> params = new HashMap<>();
params.put("name", name);
params.put("birth_date", birthdate);
params.put("address", address);
params.put("number", number);
params.put("gender", gender);
params.put("occupation", occupation);
params.put("id", id);
return params;
}
};
RequestQueue requestQueue = Volley.newRequestQueue(getActivity());
requestQueue.add(stringRequest);
}
}
I know I got too much code but all I am just needing is that when I click on the save edit I just wish that the mainfragment will be refreshed. or I just wished I can add the one like other apps like when I drag down the fragment refreshes.
This is just solved by getting my php codes right! :)
Seeing what table name i got and it's column names :) just be careful of what you put on guys! hihi
I created a new Activity once a Login is successful. But when I start the app, the app crash within 5 seconds with the message
Attempt to invoke virtual method 'java.lang.String android.os.Bundle.getString(java.lang.String)' on a null object reference
Error is coming from this
name.setText(" "+bundle.getString("name"));
public class LoginActivity extends Activity {
public ImageView bgLogo;
Button login_button;
EditText Username, Password;
String username, password;
String login_url = "http://192.168.0.19/login.php";
AlertDialog.Builder builder;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE); // Enlever la barre bleue
setContentView(R.layout.activity_login);
initExit ();
builder = new AlertDialog.Builder(LoginActivity.this);
login_button = (Button) findViewById(R.id.bLogin);
Username = (EditText) findViewById(R.id.etUsername);
Password = (EditText) findViewById(R.id.etPassword);
login_button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
username = Username.getText().toString();
password = Password.getText().toString();
if (username.equals("") || password.equals("")) {
builder.setTitle("Mince une erreur...");
displayAlert("Veuillez entrer un username et un mot de passe correct...");
}
else {
StringRequest stringRequest = new StringRequest(Request.Method.POST, login_url,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
JSONArray jsonArray = null;
try {
jsonArray = new JSONArray(response);
JSONObject jsonObject = jsonArray.getJSONObject(0);
String code = jsonObject.getString("code");
if (code.equals("login_failed")) {
builder.setTitle("Erreur d'authentification");
displayAlert(jsonObject.getString("message"));
}
else {
Intent intent = new Intent (LoginActivity.this, UserAreaActivity.class);
Bundle bundle = new Bundle();
bundle.putString("name", jsonObject.getString("name"));
intent.putExtras(bundle);
startActivity(intent);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(LoginActivity.this, "Erreur", Toast.LENGTH_LONG).show();
error.printStackTrace();
}
})
{
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map <String, String> params = new HashMap<String, String>();
params.put("user_name", username);
params.put("password", password);
return params;
}
};
MySingleton.getInstance(LoginActivity.this).addToRequestque(stringRequest);
}
}
});
}
private void initExit() {
bgLogo = (ImageView) findViewById(R.id.bgLogo1);
bgLogo.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick (View v) {
Intent intent = new Intent (LoginActivity.this, MainActivity.class);
startActivity(intent);
}
});
}
public void displayAlert (String message) {
builder.setMessage(message);
builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Username.setText("");
Password.setText("");
}
});
AlertDialog alertDialog = builder.create();
alertDialog.show();
}
#Override
public void onBackPressed() {
// do nothing.
Intent intent = new Intent(LoginActivity.this, MainActivity.class);
startActivity(intent);
return;
}
}
public class UserAreaActivity extends Activity {
public ImageView bgNet;
public ImageView bgChat;
public ImageView bgStats;
public ImageView bgGo;
public Button bLogout;
TextView name;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE); // Enlever la barre bleue
setContentView(R.layout.activity_user_area);
name = (TextView) findViewById(R.id.name);
Bundle bundle = getIntent().getExtras();
name.setText(" "+bundle.getString("name"));
initGoHome ();
initPlay ();
initGoStats ();
initGoChat ();
buttonLogout ();
}
#Override
public void onBackPressed() {
return;
}
private void initGoHome () {
bgNet = (ImageView) findViewById(R.id.bgNet);
bgNet.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick (View v) {
Intent intent = new Intent (UserAreaActivity.this, HomeActivity.class);
startActivity(intent);
}
});
}
private void initPlay () {
bgGo = (ImageView) findViewById(R.id.bgGo);
bgGo.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick (View v) {
Intent intent = new Intent (UserAreaActivity.this, PlayActivity.class);
startActivity(intent);
}
});
}
private void initGoStats () {
bgStats = (ImageView) findViewById(R.id.bgStats);
bgStats.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick (View v) {
Intent intent = new Intent (UserAreaActivity.this, StatsActivity.class);
startActivity(intent);
}
});
}
private void initGoChat () {
bgChat = (ImageView) findViewById(R.id.bgChat);
bgChat.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick (View v) {
Intent intent = new Intent (UserAreaActivity.this, ChatActivity.class);
startActivity(intent);
}
});
}
private void buttonLogout () {
bLogout = (Button) findViewById(R.id.bLogout);
bLogout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick (View v) {
Intent intent = new Intent (UserAreaActivity.this, MainActivity.class);
startActivity(intent);
}
});
}
}
Replace this code snippet:
Bundle bundle = getIntent().getExtras();
name.setText(" "+bundle.getString("name"));
with
Bundle bundle = getIntent().getExtras();
if (bundle != null)
{
name.setText(" "+bundle.getString("name"));
}
Your problem will be solved.
Attempt to invoke virtual method 'java.lang.String
android.os.Bundle.getString(java.lang.String)' on a null object
reference
Well, you need to avoid calling a method on a null object. In your case:
name.setText(" "+bundle.getString("name"));
The bundle is a null object in this case. So it throws an error.
The solution to avoid this crash is to add a if/else statement
if (bundle != null)
// set text for name like what you have done
else
// set a default text for name
But, I suggest it's better to check your code and understand why your bundle is getting null.
The code is resolved for me by typing
in Activity where you get the value by bundle
Bundle bundle = getIntent().getExtras();
hName = bundle.getString("sharedName");
b1 =new Bundle(); //this b1 should be declared Globally where you are getting value
b1.putString("sharedName",hName);
Replace this code snippet:
"class".with(getActivity())
.using(Album.class)
.bucketId(Application.getBucketId())
.entityId(getArguments().getString(YourActivity.GALLERY_ID))
.retrieve(new XXXX()); Change code : Use Bundle method To replace code below type Bundle bundle = getArguments();
"example".with(getActivity())
.using(Album.class)
.bucketId(Application.getBucketId())
.entityId(bundle.getString(YourActivity.GALLERY_ID))
.retrieve(new XXXX());
I am trying to load some items from JSON, I am able to get and parse the JSON and load it up in listview when using one activity. However, I want to use a LoadJSON.class to load the JSON, and then the activity can call the json passed and show it in the listview in that activity.
Here is what I have tried:
SongsManager.class
public class SongsManager {
private String TAG = SongsManager.class.getSimpleName();
private static final String API_URL = "http://xxxxxxxxxxxxx.com/jame/mp3/songlist.json";
private List<SolTracks> solTracksList;
private ProgressDialog pDialog;
private final Activity activity;
public SongsManager(Activity activity) {
this.activity = activity;
solTracksList = new ArrayList<>();
pDialog = new ProgressDialog(activity);
fetchSongs();
}
private void fetchSongs() {
pDialog.setMessage("Fetching Playlist...");
pDialog.show();
// Volley's json array request object
JsonArrayRequest req = new JsonArrayRequest(API_URL,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
Log.d(TAG, "Responser = " + response.toString());
pDialog.hide();
if (response.length() > 0) {
// looping through json and adding to movies list
for (int i = 0; i < response.length(); i++) {
try {
JSONObject movieObj = response.getJSONObject(i);
String songTitle = movieObj.getString("title");
String songId = movieObj.getString("id");
String streamUrl = movieObj.getString("stream_url");
SolTracks m = new SolTracks(songTitle, songId, streamUrl);
solTracksList.add(m);
Collections.sort(solTracksList, new TrackComparator());
} catch (JSONException e) {
Log.e(TAG, "JSON Parsing error: " + e.getMessage());
}
}
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e(TAG, "Server Error: " + error.getMessage());
pDialog.hide();
Snackbar snackbar = Snackbar
.make(activity.findViewById(android.R.id.content), "PLEASE CHECK YOUR INTERNET", Snackbar.LENGTH_LONG)
.setAction("DISMISS", new View.OnClickListener() {
#Override
public void onClick(View view) {
}
});
// Changing snackbar background
snackbar.getView().setBackgroundColor(ContextCompat.getColor(activity, R.color.colorPrimary));
// Changing message text color
snackbar.setActionTextColor(Color.YELLOW);
// Changing action button text color
View sbView = snackbar.getView();
TextView textView = (TextView) sbView.findViewById(android.support.design.R.id.snackbar_text);
textView.setTextColor(Color.WHITE);
snackbar.show();
}
});
req.setRetryPolicy(new DefaultRetryPolicy(0, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
// Adding request to request queue
AppController.getInstance().addToRequestQueue(req);
}
public List<SolTracks> getList() {
return solTracksList;
}
Activity class
public class TheMain1 extends AppCompatActivity {
private SwipeRefreshLayout swipeRefreshLayout;
private String TAG = TheMain1.class.getSimpleName();
private static final String API_URL = "http://xxxxxxxxxxx.com/jame/mp3/songlist.json";
private ListView listView;
private SolTracksAdapter adapter;
private ProgressDialog pDialog;
private List<SolTracks> songslist;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_the_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
listView = (ListView) findViewById(R.id.track_list_view);
songslist = new ArrayList<>();
SongsManager songsManager = new SongsManager(this);
songslist = songsManager.getList();
adapter = new SolTracksAdapter(this, songslist);
listView.setAdapter(adapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener()
{
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
SolTracks track = songslist.get(position);
final String stream_url = track.stream_url;
final String id_url = track.id;
Intent intent = new Intent(TheMain1.this, PlayerActivity.class);
intent.putExtra("songPosition", position);
intent.putExtra("streamUrl", stream_url);
startActivity(intent);
}
}
);
}
As it is right now, I know the JSON is loaded from SongsManager, but its just not displaying in the listview of the Activity class. Can anyone help, and show what I'm doing wrong? Thanks
I was able to fix this by implementing Parcelable to send the list to the receiving activity.
public class SolTracks implements Parcelable {
public String title;
public String id;
public String stream_url;
}
Sending the list from the Activity A:
Intent intent = new Intent(TheMain.this, PlayerActivity.class);
Bundle bundle = new Bundle();
bundle.putParcelableArrayList("mylist", solTracksList);
intent.putExtras(bundle);
intent.putExtra("songPosition", position);
startActivity(intent);
and then receiving in Activity B:
Bundle extras = getIntent().getExtras();
if (extras != null) {
songPosition = extras.getInt("songPosition");
trackList = extras.getParcelableArrayList("mylist");
}
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