Im trying to get a single value from JSON using Retrofit, i followed a tutorial but i got an error saying that "Class anonymous class derived from Callback must be either declared ...." .
what im specifically trying to achieve is to echo a single json property value in a empty string like String Axe = ""; and i fill it with a specific value from the json file from the server. here is what i tried.
Json format
"axe1": {"test1"}
The ApiInterface
import com.google.gson.JsonObject;
import retrofit2.Call;
import retrofit2.http.GET;
public interface ApiInterface {
#GET("test.json")
Call<JsonObject> readJsonFromFileUri();
}
The MainActivity
import android.graphics.Typeface;
import android.os.Build;
import android.support.v7.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.preference.PreferenceManager;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.TextView;
import com.android.volley.Response;
import com.google.gson.Gson;
import com.google.gson.JsonObject;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;
public class MainActivity extends ActionBarActivity {
DataBaseHandler db;
private AlertDialog dialog;
public static final int IntialQteOfDayId = 8;
private ImageView btn_quotes, btn_authors, btn_favorites, btn_categories, btn_qteday, btn_rateus ;
final Context context = this;
SharedPreferences preferences;
private static final int RESULT_SETTINGS = 1;
// URL of object to be parsed
// This string will hold the results
String data = "";
class Myads{
String bnr;
String intt;
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
getWindow().addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
getWindow().setStatusBarColor(getResources().getColor(R.color.colorPrimaryDark));
}
Retrofit retrofit = new Retrofit.Builder()
.baseUrl("https://yourdomain.com/s/ ")
.addConverterFactory(GsonConverterFactory.create())
.build();
ApiInterface apiInterface = retrofit.create(ApiInterface.class);
Call<JsonObject> jsonCall = apiInterface.readJsonFromFileUri();
jsonCall.enqueue(new Callback<JsonObject>() {
#Override
public void onResponse(Call<JsonObject> call, Response<JsonObject> response) {
JsonObject json = new JsonObject(body().toString());
Gson gson = new Gson();
Myads ad = gson.fromJson(jsonString, Myads.class);
Log.i(LOG_TAG, String.valueOf(ad.bnr));
}
#Override
public void onFailure(Call<JsonObject> call, Throwable t) {
Log.e(LOG_TAG, t.toString());
}
});
Typeface bold = Typeface.createFromAsset(getAssets(),
"fonts/extrabold.otf");
db = new DataBaseHandler(this);
db.openDataBase() ;
TextView cat = (TextView) findViewById(R.id.titlecat);
cat.setTypeface(bold);
TextView alls = (TextView) findViewById(R.id.titlest);
alls.setTypeface(bold);
TextView fav = (TextView) findViewById(R.id.titlefav);
fav.setTypeface(bold);
TextView qday = (TextView) findViewById(R.id.titleqday);
qday.setTypeface(bold);
TextView rate = (TextView) findViewById(R.id.titleqrate);
rate.setTypeface(bold);
btn_quotes = (ImageView) findViewById(R.id.btn_quotes);
//btn_authors= (Button) findViewById(R.id.btn_authors);
btn_categories = (ImageView) findViewById(R.id.btn_categories);
btn_favorites = (ImageView) findViewById(R.id.btn_favorites);
btn_qteday = (ImageView) findViewById(R.id.btn_qteday);
btn_rateus = (ImageView) findViewById(R.id.btn_rateus);
btn_quotes.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(MainActivity.this,
QuotesActivity.class);
intent.putExtra("mode", "allQuotes");
startActivity(intent);
}
});
/*btn_authors.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent author = new Intent(MainActivity.this,
AuteursActivity.class);
startActivity(author);
}
});*/
btn_favorites.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent favorites = new Intent(MainActivity.this,
QuotesActivity.class);
favorites.putExtra("mode", "isFavorite");
startActivity(favorites);
}
});
btn_categories.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent category = new Intent(MainActivity.this,
CategoryActivity.class);
startActivity(category);
}
});
btn_qteday.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
preferences = PreferenceManager
.getDefaultSharedPreferences(context);
Intent qteDay = new Intent(MainActivity.this,
QuoteActivity.class);
qteDay.putExtra("id",
preferences.getInt("id", IntialQteOfDayId));
qteDay.putExtra("mode", "qteday");
startActivity(qteDay);
}
});
btn_rateus.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
AlertDialog.Builder builder = new AlertDialog.Builder(
MainActivity.this);
builder.setMessage(getResources().getString(
R.string.ratethisapp_msg));
builder.setTitle(getResources().getString(
R.string.ratethisapp_title));
builder.setPositiveButton(
getResources().getString(R.string.rate_it),
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog,
int which) {
// TODO Auto-generated method stub
Intent fire = new Intent(
Intent.ACTION_VIEW,
Uri.parse("http://play.google.com/store/apps/details?id=" + getPackageName())); //dz.amine.thequotesgarden"));
startActivity(fire);
}
});
builder.setNegativeButton(
getResources().getString(R.string.cancel),
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog,
int which) {
// TODO Auto-generated method stub
dialog.dismiss();
}
});
dialog = builder.create();
dialog.show();
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.menu_settings) {
Intent i = new Intent(this, UserSettingActivity.class);
startActivityForResult(i, RESULT_SETTINGS);
}
return super.onOptionsItemSelected(item);
}
}
So, i want the value of Json axe1 which is test1 to be parsed and put in into the empty string
You are using wrong import:
import com.android.volley.Response;
Replace it with
import retrofit2.Response;
Firstly, your JSON format is invalid, it should be {"axe1": "test1"}.
To store it you could do :
JSONObject json = new JSONObject(response.body().toString());
Log.i(LOG_TAG, json.getString("axe1"));
Related
All my pages use onSupportNavigateUp() function with the same method and it's working. However when I tried to implement in my LessonActivity.java it's not working. Any ideas? It's it because of WebView?
My current working codes for LessonActivity.java:
package com.activity.lesson;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.design.widget.BottomNavigationView;
import android.support.design.widget.BottomSheetBehavior;
import android.support.design.widget.BottomSheetDialog;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.AppCompatRatingBar;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.PopupMenu;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ServerValue;
import com.google.firebase.database.ValueEventListener;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.material.components.R;
import com.material.components.activity.pastyears.PastYears;
import com.material.components.activity.practice.Practice;
import com.material.components.adapter.AdapterQuestionToTeacher;
import com.material.components.model.Lessons;
import com.material.components.model.QuestionsToTeacher;
import com.material.components.model.SubChapter;
import com.material.components.utils.Tools;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
public class LessonActivity extends AppCompatActivity{
public WebView contentWebView;
public ProgressBar progressBar;
public String chapterTitle;
private SharedPreferences analysisSharedPreferences;
private SharedPreferences.Editor editorAnalysisPreferences;
private BottomSheetBehavior mBehavior;
private BottomSheetDialog mBottomSheetDialog;
private View bottom_sheet;
private BottomNavigationView navigation;
public ArrayList<QuestionsToTeacher> questionsToTeacherList = new ArrayList<>();
private AdapterQuestionToTeacher adapterQuestionToTeacher;
private RecyclerView questionListRecyclerView;
private String subjectId;
private String chapterId;
private String subchapterId;
private TextView question_content;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_lesson);
contentWebView = findViewById(R.id.contentWebView);
progressBar = findViewById(R.id.progressBarContent);
question_content = findViewById(R.id.question_content);
Tools.setSystemBarColor(this,R.color.black);
String qContent = question_content.getText().toString().trim();
if(qContent.isEmpty())
{
question_content.setVisibility(View.GONE);
}else
{
question_content.setVisibility(View.VISIBLE);
}
initToolbar();
String subChapterId = getIntent().getStringExtra("subchapter_id");
getLessonData(subChapterId);
analysisSharedPreferences = getApplicationContext().getSharedPreferences("AnalysisSharedPreferences",MODE_PRIVATE);
editorAnalysisPreferences = analysisSharedPreferences.edit();
subjectId = analysisSharedPreferences.getString("subjectId","");
chapterId = analysisSharedPreferences.getString("chapterId","");
subchapterId = analysisSharedPreferences.getString("subchapterId","");
bottom_sheet = findViewById(R.id.bottom_sheet);
mBehavior = BottomSheetBehavior.from(bottom_sheet);
navigation = findViewById(R.id.navigation);
navigation.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
switch (item.getItemId()) {
case R.id.navigation_question_list:
showQuestionList();
return true;
}
return false;
}
});
}
private void getQuestionList() {
GsonBuilder builder = new GsonBuilder();
final Gson gson = builder.create();
questionsToTeacherList.clear();
FirebaseDatabase firebaseDatabase = FirebaseDatabase.getInstance();
DatabaseReference databaseReference = firebaseDatabase.getReference();
FirebaseAuth firebaseAuth = FirebaseAuth.getInstance();
databaseReference.child("ask_teachers/students/"+firebaseAuth.getUid()+"/subjects/"+subjectId+"/chapters/"+chapterId+"/subchapters/"+subchapterId+"/questions").addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot snapshot: dataSnapshot.getChildren())
{
String dataReceived = gson.toJson(snapshot.getValue());
System.out.println(snapshot.getValue());
QuestionsToTeacher questionsToTeacher = gson.fromJson(dataReceived,QuestionsToTeacher.class);
questionsToTeacherList.add(questionsToTeacher);
}
adapterQuestionToTeacher.notifyDataSetChanged();
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
private void showQuestionList() {
if (mBehavior.getState() == BottomSheetBehavior.STATE_EXPANDED) {
mBehavior.setState(BottomSheetBehavior.STATE_COLLAPSED);
}
final View view = getLayoutInflater().inflate(R.layout.sheet_question_list, null);
adapterQuestionToTeacher = new AdapterQuestionToTeacher(questionsToTeacherList);
RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(LessonActivity.this);
questionListRecyclerView = view.findViewById(R.id.questionListRecyclerView);
questionListRecyclerView.setItemAnimator(new DefaultItemAnimator());
questionListRecyclerView.setNestedScrollingEnabled(false);
questionListRecyclerView.setHasFixedSize(true);
questionListRecyclerView.setLayoutManager(layoutManager);
questionListRecyclerView.setAdapter(adapterQuestionToTeacher);
adapterQuestionToTeacher.setOnClickListener(new AdapterQuestionToTeacher.OnClickListener() {
#Override
public void onItemClick(View view, QuestionsToTeacher obj, int pos) {
question_content.setVisibility(View.VISIBLE);
question_content.setText(obj.messages);
mBottomSheetDialog.dismiss();
}
});
(view.findViewById(R.id.bt_close)).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
mBottomSheetDialog.dismiss();
}
});
mBottomSheetDialog = new BottomSheetDialog(this);
mBottomSheetDialog.setContentView(view);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
mBottomSheetDialog.getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
}
mBottomSheetDialog.show();
mBottomSheetDialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
#Override
public void onDismiss(DialogInterface dialog) {
mBottomSheetDialog = null;
}
});
getQuestionList();
}
private void getLessonData(String subChapterId)
{
FirebaseDatabase.getInstance().getReference().child("lessons/"+subChapterId+"/lessons_data")
.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
String lessonDisplay = "";
for(DataSnapshot snapshot: dataSnapshot.getChildren())
{
System.out.println("lesson_inner_content");
System.out.println(snapshot.getValue());
lessonDisplay += snapshot.getValue();
}
contentWebView.getSettings().setJavaScriptEnabled(true);
contentWebView.setWebViewClient(new AppWebViewClients(progressBar));
contentWebView.loadData(String.valueOf(lessonDisplay),"text/html", "UTF-8");
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
public class AppWebViewClients extends WebViewClient {
private ProgressBar progressBar;
public AppWebViewClients(ProgressBar progressBar) {
this.progressBar=progressBar;
progressBar.setVisibility(View.VISIBLE);
}
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
// TODO Auto-generated method stub
view.loadUrl(url);
return true;
}
#Override
public void onPageFinished(WebView view, String url) {
// TODO Auto-generated method stub
super.onPageFinished(view, url);
progressBar.setVisibility(View.GONE);
}
}
private void initToolbar() {
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setHomeButtonEnabled(true);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
chapterTitle = getIntent().getStringExtra("subChapterTitle");
setTitle(chapterTitle);
}
#Override
public boolean onSupportNavigateUp() {
onBackPressed();
return true;
}
public void openSubMenu(View v)
{
PopupMenu popup = new PopupMenu(v.getContext(), v);
MenuInflater inflater = popup.getMenuInflater();
inflater.inflate(R.menu.menu_lesson_more, popup.getMenu());
popup.show();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_lesson,menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if(id == R.id.askTeacher)
{
showQuestionEntryDialog();
}
if(id == R.id.practice)
{
Intent gotoPractice = new Intent(LessonActivity.this, Practice.class);
startActivity(gotoPractice);
}
if(id == R.id.pastYears)
{
Intent gotoPastYears = new Intent(LessonActivity.this, PastYears.class);
startActivity(gotoPastYears);
}
return true;
}
private void showQuestionEntryDialog() {
final Dialog dialog = new Dialog(this);
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE); // before
dialog.setContentView(R.layout.dialog_ask_teacher_question_entry);
dialog.setCancelable(true);
WindowManager.LayoutParams lp = new WindowManager.LayoutParams();
lp.copyFrom(dialog.getWindow().getAttributes());
lp.width = WindowManager.LayoutParams.WRAP_CONTENT;
lp.height = WindowManager.LayoutParams.WRAP_CONTENT;
final EditText et_post = dialog.findViewById(R.id.et_post);
dialog.findViewById(R.id.bt_cancel).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
dialog.dismiss();
}
});
dialog.findViewById(R.id.bt_submit).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String review = et_post.getText().toString().trim();
if (review.isEmpty()) {
Toast.makeText(getApplicationContext(), "Please fill review text", Toast.LENGTH_SHORT).show();
}else
{
submitQuestion(review, dialog);
}
}
});
dialog.show();
dialog.getWindow().setAttributes(lp);
}
private void submitQuestion(String message, final Dialog dialog)
{
FirebaseDatabase firebaseDatabase = FirebaseDatabase.getInstance();
FirebaseUser currentFirebaseUser = FirebaseAuth.getInstance().getCurrentUser();
String uuid = currentFirebaseUser.getUid();
DatabaseReference databaseReference = firebaseDatabase.getReference();
HashMap<Object,Object> messagesData = new HashMap<>();
messagesData.put("subject_id",subjectId);
messagesData.put("chapter_id",chapterId);
messagesData.put("subchapter_id",subchapterId);
messagesData.put("messages",message);
messagesData.put("status","pending");
messagesData.put("dt_added", ServerValue.TIMESTAMP);
databaseReference.child("ask_teachers/students/"+uuid+"/subjects/"+subjectId+"/chapters/"+chapterId+"/subchapters/"+subchapterId+"/questions/").push().setValue(messagesData, new DatabaseReference.CompletionListener(){
#Override
public void onComplete(DatabaseError databaseError, DatabaseReference databaseReference) {
Toast.makeText(LessonActivity.this, "Successfully added to Ask Teacher list", Toast.LENGTH_SHORT).show();
dialog.dismiss();
}
});
}
}
onSupportNavigateUp() is not working because you're also overriding onOptionsItemSelected(). Since you return true; from onOptionsItemSelected(), you basically tell Android that you handle all item clicks by yourself and it doesn't need to do something.
You have two options now. Either call super.onOptionsItemSelected() like:
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.askTeacher) {
showQuestionEntryDialog();
return true; // don't forget to return true after your action
}
// ... handle all your other items
return super.onOptionsItemSelected(item);
}
Or you handle the back button click by yourself:
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
// navigate up on back button click
if (id == android.R.id.home) {
NavUtils.navigateUpFromSameTask(this);
return true;
}
// ... handle all your other items
return true;
}
By the way, I think overriding onSupportNavigateUp() is not needed at all. Up navigation works "out of the box" (at least for me), as long as I don't override onOptionsItemSelected() or call super.onOptionsItemSelected(item); from within it.
I am trying to save a string in sharedPreferences. I don't know what I did wrong but it doesn't save the String value.
this is the code
here I am saving String value "phone". notice its Fragment page
package com.world.bolandian.watchme;
import android.app.Fragment;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import com.google.gson.Gson;
public class LoginFragment extends Fragment implements Listen {
Button loginBtn;
ServerRequest ser;
Connector c;
LoginCommunicationThread loginT;
private LoginUser logUser;
EditText phone,password;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_login, container, false);
}
public void setInterface(Connector c){
this.c=c;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
ser=new ServerRequest();
ser.addServerName(Params.SERVER_URL);
ser.addServletName(Params.LOGIN_SERVLET);
ser.setResponse(this);
loginT = new LoginCommunicationThread(ser);
phone = (EditText)getActivity().findViewById(R.id.userTxt);
password = (EditText)getActivity().findViewById(R.id.passwordTxt);
loginBtn = (Button) getActivity().findViewById(R.id.loginBtn);
loginBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//save phone number in sharedpreferences
SharedPreferences pref = getActivity().getPreferences(0);
SharedPreferences.Editor edt = pref.edit();
edt.putString("PHONE",String.valueOf(phone.getText()));
edt.commit();
Context context = getActivity();
PreferenceManager.getDefaultSharedPreferences(context).edit().putString("PHONE", String.valueOf(phone.getText()));
logUser = new LoginUser(phone.getText().toString(),password.getText().toString());
if (phone.getText().toString() == null)
{
Toast.makeText(getActivity(),"Please enter phone number", Toast.LENGTH_LONG).show();
}
if(password.getText().toString() == null)
{
Toast.makeText(getActivity(),"Please enter password", Toast.LENGTH_LONG).show();
}
else {
Gson g = new Gson();
String ans = g.toJson(logUser, LoginUser.class);
login(logUser);
}
}
});
}
public void login (LoginUser user)
{
LoginCommunicationThread con;
ServerRequest ser = new ServerRequest();
ser.setResponse(this);
Gson gson = new Gson();
String send = gson.toJson(user,LoginUser.class);
ser.addParamaters(Params.USER,send);
ser.addServerName(Params.SERVER_URL);
ser.addServletName(Params.LOGIN_SERVLET);
con = new LoginCommunicationThread(ser);
con.start();
}
#Override
public void good() {
Toast.makeText(getActivity(), "Welcome", Toast.LENGTH_LONG).show();
Intent i = new Intent(getActivity(),MainActivity.class);
startActivity(i);
}
#Override
public void notGood() {
Toast.makeText(getActivity(),"Wrong password or phone",Toast.LENGTH_LONG).show();
}
#Override
public void notGoodServerEroorr() {
Toast.makeText(getActivity(), "Connection Error please try again", Toast.LENGTH_LONG);
}
}
Here i extract the value "PHONE" but i keep getting null. for some reason it doesnt get the value and the default is null (This page is Activity)
package com.world.bolandian.watchme;
import android.app.Activity;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.TabHost;
import android.widget.TextView;
import com.google.gson.Gson;
public class MainActivity extends Activity implements Listen {
private LockAndUnLock sendnotf;
TextView status;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
status = (TextView)findViewById(R.id.status);
TabHost tabHost = (TabHost) findViewById(R.id.tabHost);
tabHost.setup();
TabHost.TabSpec tabspec = tabHost.newTabSpec("main");
tabspec.setContent(R.id.main);
tabspec.setIndicator("Main");
tabHost.addTab(tabspec);
tabspec = tabHost.newTabSpec("gps");
tabspec.setContent(R.id.GPS);
tabspec.setIndicator("GPS");
tabHost.addTab(tabspec);
tabspec = tabHost.newTabSpec("info");
tabspec.setContent(R.id.INFO);
tabspec.setIndicator("Info");
tabHost.addTab(tabspec);
}
public void Lock (View view)
{
SharedPreferences sharedPreferences =
PreferenceManager.getDefaultSharedPreferences(this);
String phone = sharedPreferences.getString("PHONE", null);
PreferenceManager.getDefaultSharedPreferences(this).getString("PHONE",
null);
sendnotf = new LockAndUnLock(phone,1); // 1 = true = lock
Gson g = new Gson();
String ans=g.toJson(sendnotf, LockAndUnLock.class);
sendLockAndUnlock(sendnotf);
if (status.getVisibility() != View.VISIBLE) {
status.setVisibility(View.VISIBLE);
}
status.setText("LOCKED");
status.setTextColor(Color.RED);
}
public void UnLock (View view)
{
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
String phone = sharedPreferences.getString("PHONE",null);
sendnotf = new LockAndUnLock(phone,0); // 0 = false = unlock
Gson g = new Gson();
String ans=g.toJson(sendnotf, LockAndUnLock.class);
sendLockAndUnlock(sendnotf);
if (status.getVisibility() != View.VISIBLE) {
status.setVisibility(View.VISIBLE);
}
status.setText("OPEN");
status.setTextColor(Color.GREEN);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public void good() {
}
#Override
public void notGood() {
}
#Override
public void notGoodServerEroorr() {
}
public void sendLockAndUnlock(LockAndUnLock sendnotf){
RegisterCommunicationThread con;
ServerRequest ser = new ServerRequest();
ser.setResponse(this);
Gson gson = new Gson();
String send = gson.toJson(sendnotf, LockAndUnLock.class);
ser.addParamaters(Params.LOCKANDUNLOCK,send);
ser.addServerName(Params.SERVER_URL);
ser.addServletName(Params.LOCKANDUNLOCK_SERVLET);
con = new RegisterCommunicationThread(ser);
con.start();
}
}
Problem is with different shared preferences objects. According to official documentation:
getPreferences (int mode)
Added in API level 1 Retrieve a SharedPreferences object for accessing
preferences that are private to this activity. This simply calls the
underlying getSharedPreferences(String, int) method by passing in this
activity's class name as the preferences name.
My suggestion is to use special entity for handling shared preferences. In your case it may look like following code
public class SharedPreferencesManager {
private static final String PREFERENCES_NAME = "your_name";//name for xml file
private final SharedPreferences sharedPreferences;
public SharedPreferencesManager(Context context) {
sharedPreferences = context.getSharedPreferences(PREFERENCES_NAME, Context.MODE_PRIVATE);
}
public String getPhone() {
return sharedPreferences.getString("PHONE", null);
}
public void savePhone(#NonNull String phone) {
sharedPreferences.edit().putString("PHONE", phone).apply(); //or commit for blocking save
}
}
Then replace all your direct call to SharedPreferences in Activity, Fragment with above object.
I'm finishing an app, and now I want to add a progressbar or something like the Material Design Loading circle. I'm gonna use it while the user login.The LoginActivity works basically like this: when the user hits the ok button, an ASyncTask gets some data from my API. What I want is to show a progressBar while the ASyncTask makes the inquiry to my API and recieves back the data. I've try some libraries and some tutorials but didn't get any results.This is my LoginActivity:
package com.tumta.henrique.teste.view;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.os.Build;
import android.support.v7.app.ActionBar;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.view.inputmethod.EditorInfo;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.TextView;
import com.tumta.henrique.teste.R;
import com.tumta.henrique.teste.model.ConsultaLogin;
import com.tumta.henrique.teste.util.Connectivity;
import java.util.List;
public class LoginActivity extends ActionBarActivity implements ConsultaLogin.ConsultaConcluidaLoginListener {
EditText txtUsuario, txtSenha;
ActionBar actionbar;
Button btnOk, btnCancelar;
private AlertDialog alerta;
String login, senha;
Connectivity conn = new Connectivity();
#Override
protected void onCreate(Bundle savedInstanceState) {
if (Build.VERSION.SDK_INT >= 21) {
Window window = this.getWindow();
window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
window.setStatusBarColor(this.getResources().getColor(R.color.azul_nav));
}
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
txtUsuario = (EditText) findViewById(R.id.edit_usuario);
txtSenha = (EditText) findViewById(R.id.edit_senha);
txtUsuario.setOnEditorActionListener(new TextView.OnEditorActionListener() {
public boolean onEditorAction(TextView v, int actionId,
KeyEvent event) {
if (actionId == EditorInfo.IME_ACTION_GO) {
txtSenha.requestFocus();
return true;
}
return false;
}
});
txtSenha.setOnEditorActionListener(new TextView.OnEditorActionListener() {
public boolean onEditorAction(TextView v, int actionId,
KeyEvent event) {
if (actionId == EditorInfo.IME_ACTION_GO) {
onClickOk(v);
return true;
}
return false;
}
});
actionbar = getSupportActionBar();
actionbar.hide();
btnOk = (Button) findViewById(R.id.button_ok);
btnCancelar = (Button) findViewById(R.id.button_cancelar);
boolean isConnected = conn.isConnected(this);
if(isConnected == false){
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Erro");
builder.setMessage(R.string.aviso_rede);
builder.setPositiveButton(R.string.config, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
startActivityForResult(new Intent(android.provider.Settings.ACTION_SETTINGS), 0);
}
});
builder.setNegativeButton("Sair", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
finish();
}
});
alerta = builder.create();
alerta.show();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_login, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
public void onClickOk(View view) {
try {
if (txtUsuario.getText().toString().equals("") || txtSenha.getText().toString().equals("")) {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Erro");
builder.setMessage("Preencha todos os campos!");
builder.setNeutralButton("Ok", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
login = "";
senha = "";
txtSenha.getText().clear();
txtUsuario.requestFocus();
}
});
alerta = builder.create();
alerta.show();
} else {
login = txtUsuario.getText().toString();
senha = txtSenha.getText().toString();
ConsultaLogin.URL_STRING = "http://186.207.85.205:7001/com.henrique.rest/api/v1/status/login?usu_login="
+ login + "&usu_senha=" + senha;
new ConsultaLogin(this).execute();
}
} catch (Exception e) {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Erro");
builder.setMessage("Ocorreu um erro inesperado! \nTente novamente.");
builder.setNeutralButton("Ok", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
login = "";
senha = "";
txtUsuario.getText().clear();
txtSenha.getText().clear();
txtUsuario.requestFocus();
}
});
alerta = builder.create();
alerta.show();
}
}
public void onClickCancelar(View view) {
finish();
}
#Override
public void onConsultaConcluida(List<String> result) {
if (result.isEmpty()) {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Erro");
builder.setMessage("Usuario ou Senha Incorreto!");
builder.setNeutralButton("Ok", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
login = "";
senha = "";
txtSenha.getText().clear();
txtUsuario.requestFocus();
}
});
alerta = builder.create();
alerta.show();
} else {
Intent intent = new Intent(this, MainActivity.class);
startActivity(intent);
}
}
}
And this is my ASyncTask:
package com.tumta.henrique.teste.model;
import android.os.AsyncTask;
import android.util.Log;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
/**
* Created by Henrique on 16/06/2015.
*/
public class ConsultaLogin extends AsyncTask<Void, Void, List<String>> {
private ConsultaConcluidaLoginListener listener;
//public static String login, senha;
public static String URL_STRING = "";
public ConsultaLogin(ConsultaConcluidaLoginListener listener) {
this.listener = listener;
}
#Override
protected List<String> doInBackground(Void... arg0) {
try {
String resultado = ConsultaServidor();
return InterpretaResultado(resultado);
} catch (IOException e) {
Log.e("Erro", "Ocorreu um erro na consulta ao servidor!", e);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
private List<String> InterpretaResultado(String resultado) throws JSONException {
JSONObject object = new JSONObject(resultado);
JSONArray jsonArray = object.getJSONArray("login");
List<String> listaLogin = new ArrayList<>();
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonLogin = jsonArray.getJSONObject(i);
if (jsonLogin.has("usu_nome")) {
String nome = jsonLogin.getString("usu_nome");
listaLogin.add(i, nome);
} else listaLogin.clear();
}
return listaLogin;
}
private String ConsultaServidor() throws IOException {
InputStream is = null;
try {
URL url = new URL(URL_STRING);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setConnectTimeout(10000);
conn.setReadTimeout(15000);
conn.setRequestMethod("GET");
conn.setDoInput(true);
conn.connect();
conn.getResponseCode();
is = conn.getInputStream();
Reader reader = null;
reader = new InputStreamReader(is);
char[] buffer = new char[2048];
reader.read(buffer);
return new String(buffer);
} finally {
if (is != null) {
is.close();
}
}
}
#Override
protected void onPostExecute(List<String> result) {
super.onPostExecute(result);
}
public interface ConsultaConcluidaLoginListener {
void onConsultaConcluida(List<String> result);
}
}
If you need more details, please ask.
Add the progressbar to your layout (indeterminate), and toggle visibility on when you initialize the async task. On the callback of the async, toggle the visibility off.
On request:
login = txtUsuario.getText().toString();
senha = txtSenha.getText().toString();
yourProgressBar.setVisibility(View.VISIBLE);
ConsultaLogin.URL_STRING = "http://186.207.85.205:7001/com.henrique.rest/api/v1/status/login?usu_login=" + login + "&usu_senha=" + senha;
new ConsultaLogin(this).execute();
On result:
#Override
public void onConsultaConcluida(List<String> result) {
if (result.isEmpty()) {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Erro");
builder.setMessage("Usuario ou Senha Incorreto!");
builder.setNeutralButton("Ok", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
login = "";
senha = "";
txtSenha.getText().clear();
txtUsuario.requestFocus();
}
});
alerta = builder.create();
alerta.show();
} else {
yourProgressBar.setVisibility(View.GONE);
Intent intent = new Intent(this, MainActivity.class);
startActivity(intent);
}
}
Two activities are sending data to each other.
The first activity has a custom list view. The second has one text view and three buttons to increase and decrease a value.
When I click on the first activity, the second activity opens. The second activity increases the text view value and clicked the button. Data goes to the first activity. Same process again.
My problem is that the total value is not displayed in the first activity.
How can i show all increase and decrease values from the second activity in the first activity?
First activity's code:
package com.firstchoicefood.phpexpertgroup.firstchoicefoodin;
import android.app.ActionBar;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.AsyncTask;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import android.app.Activity;
import com.firstchoicefood.phpexpertgroup.firstchoicefoodin.bean.ListModel;
import com.firstchoicefood.phpexpertgroup.firstchoicefoodin.json.JSONfunctions;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Arrays;
public class DetaisRESTActivity extends Activity {
String messagevaluename,valueid,valueid1,valuename,pos;
public String countString=null;
String nameofsubmenu;
public int count=0;
public String message=null;
public String message1=null;
JSONObject jsonobject;
JSONArray jsonarray;
ListView listview;
ArrayList aa;
public SharedPreferences.Editor edit;
public TextView mTitleTextView;
public ImageButton imageButton;
ListAdapterAddItems adapter;
public TextView restaurantname = null;
public TextView ruppees = null;
ProgressDialog mProgressDialog;
ArrayList<ListModel> arraylist;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_detais_rest);
ActionBar actionBar = getActionBar();
actionBar.setDisplayHomeAsUpEnabled(true);
actionBar.setBackgroundDrawable(new ColorDrawable(Color.parseColor("#ff0000")));
SharedPreferences preferences=getSharedPreferences("temp1", 1);
// SharedPreferences.Editor editor = preferences.edit();
int na=preferences.getInt("COUNTSTRING1",0);
Log.i("asasassas",""+na);
LayoutInflater mInflater = LayoutInflater.from(this);
View mCustomView = mInflater.inflate(R.layout.titlebar, null);
mTitleTextView = (TextView) mCustomView.findViewById(R.id.textView123456789);
imageButton = (ImageButton) mCustomView
.findViewById(R.id.imageButton2);
imageButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Toast.makeText(getApplicationContext(), "Refresh Clicked!",
Toast.LENGTH_LONG).show();
Intent i=new Intent(DetaisRESTActivity.this,TotalPriceActivity.class);
startActivity(i);
}
});
actionBar.setCustomView(mCustomView);
actionBar.setDisplayShowCustomEnabled(true);
// SqliteControllerSqliteController db = new SqliteControllerSqliteController(QuentityActivity.this);
// Reading all contacts
/*
Log.d("Reading: ", "Reading all contacts..");
List<Contact> contacts = db.getAllContacts();
for (Contact cn : contacts) {
String log = "Id: "+cn.getID()+" ,Name: " + cn.getName() + " ,Phone: " +
cn.getPhoneNumber();
// Writing Contacts to log
Log.d("Name: ", log);
}
*/
Intent intent = getIntent();
// get the extra value
valuename = intent.getStringExtra("restaurantmenuname");
valueid = intent.getStringExtra("restaurantmenunameid");
valueid1 = intent.getStringExtra("idsrestaurantMenuId5");
//totalamount = intent.getStringExtra("ruppees");
Log.i("valueid",valueid);
Log.i("valuename",valuename);
Log.i("valueid1",valueid1);
// Log.i("totalamount",totalamount);
new DownloadJSON().execute();
}
// DownloadJSON AsyncTask
private class DownloadJSON extends AsyncTask<Void,Void,Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Create a progressdialog
mProgressDialog = new ProgressDialog(DetaisRESTActivity.this);
// Set progressdialog title
mProgressDialog.setTitle("Android JSON Parse Tutorial");
// Set progressdialog message
mProgressDialog.setMessage("Loading...");
mProgressDialog.setIndeterminate(false);
// Show progressdialog
mProgressDialog.show();
Toast.makeText(DetaisRESTActivity.this, "Successs", Toast.LENGTH_LONG).show();
}
#Override
protected Void doInBackground(Void... params) {
// Create an array
arraylist = new ArrayList<ListModel>();
// Retrieve JSON Objects from the given URL address
// Log.i("123",value1);
jsonobject = JSONfunctions.getJSONfromURL("http://firstchoicefood.in/fcfapiphpexpert/phpexpert_restaurantMenuItem.php?r=" + URLEncoder.encode(valuename) + "&resid=" + URLEncoder.encode(valueid1) + "&RestaurantCategoryID=" + URLEncoder.encode(valueid) + "");
try {
// Locate the array name in JSON
jsonarray = jsonobject.getJSONArray("RestaurantMenItems");
Log.i("1234",""+jsonarray);
for (int i = 0; i < jsonarray.length(); i++) {
jsonobject = jsonarray.getJSONObject(i);
ListModel sched = new ListModel();
sched.setId(jsonobject.getString("id"));
sched.setProductName(jsonobject.getString("RestaurantPizzaItemName"));
sched.setPrice(jsonobject.getString("RestaurantPizzaItemPrice"));
arraylist.add(sched);
}
} catch (JSONException e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void args) {
// Locate the listview in listview_main.xml
listview = (ListView) findViewById(R.id.listViewdetails);
adapter = new ListAdapterAddItems();
listview.setAdapter(adapter);
// Close the progressdialog
mProgressDialog.dismiss();
adapter.notifyDataSetChanged();
listview.setOnItemClickListener(new AdapterView.OnItemClickListener()
{
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int position, long arg3)
{
// Get Person "behind" the clicked item
ListModel p =(ListModel)listview.getItemAtPosition(position);
// Log the fields to check if we got the info we want
Log.i("SomeTag",""+p.getId());
//String itemvalue=(String)listview.getItemAtPosition(position);
Log.i("SomeTag", "Persons name: " + p.getProductName());
Log.i("SomeTag", "Ruppees: " + p.getPrice());
Toast toast = Toast.makeText(getApplicationContext(),
"Item " + (position + 1),
Toast.LENGTH_SHORT);
toast.setGravity(Gravity.BOTTOM|Gravity.CENTER_HORIZONTAL, 0, 0);
toast.show();
Log.i("postititi",""+position);
Intent intent=new Intent(DetaisRESTActivity.this,QuentityActivity.class);
intent.putExtra("quentity",countString);
intent.putExtra("valueid",valueid);
intent.putExtra("valuename",valuename);
intent.putExtra("valueid1",valueid1);
intent.putExtra("id",p.getId());
intent.putExtra("name",p.getProductName());
intent.putExtra("price",p.getPrice());
startActivityForResult(intent,2);
// startActivity(intent);
}
});
}
}
// Call Back method to get the Message form other Activity
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
super.onActivityResult(requestCode, resultCode, data);
// check if the request code is same as what is passed here it is 2
if(requestCode==2)
{
pos=data.getStringExtra("POSITION");
message=data.getStringExtra("MESSAGE");
message1=data.getStringExtra("COUNTSTRING");
messagevaluename=data.getStringExtra("VALUENAME");
nameofsubmenu=data.getStringExtra("name");
Log.i("xxxxxxxxxxx",message);
Log.i("xxxxxxxxxxx1234",pos);
Log.i("xxxxxxxxxxx5678count",message1);
Log.i("messagevaluename",messagevaluename);
Log.i("submenu",nameofsubmenu);
//ruppees.setText(message);
//editor.putInt("count",na);
//editor.commit();
//Log.i("asasassasasdsasdasd",""+na);
// mTitleTextView.setText(Arrays.toString(message1));
mTitleTextView.setText(message1);
imageButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Toast.makeText(getApplicationContext(), message,
Toast.LENGTH_LONG).show();
Intent i=new Intent(DetaisRESTActivity.this,TotalPriceActivity.class);
i.putExtra("count",message1);
i.putExtra("submenu",nameofsubmenu);
i.putExtra("ruppees",message);
i.putExtra("id",pos);
i.putExtra("messagevaluename",messagevaluename);
startActivity(i);
}
});
}
}
//==========================
class ListAdapterAddItems extends ArrayAdapter<ListModel>
{
ListAdapterAddItems(){
super(DetaisRESTActivity.this,android.R.layout.simple_list_item_1,arraylist);
//imageLoader = new ImageLoader(MainActivity.this);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
final ViewHolder holder;
if(convertView == null){
LayoutInflater inflater = getLayoutInflater();
convertView = inflater.inflate(R.layout.cartlistitem, null);
holder = new ViewHolder(convertView);
convertView.setTag(holder);
}else{
holder = (ViewHolder)convertView.getTag();
}
holder.populateFrom(arraylist.get(position));
// arraylist.get(position).getPrice();
return convertView;
}
}
class ViewHolder {
ViewHolder(View row) {
restaurantname = (TextView) row.findViewById(R.id.rastaurantnamedetailsrestaurant);
ruppees = (TextView) row.findViewById(R.id.rastaurantcuisinedetalsrestaurant);
}
// Notice we have to change our populateFrom() to take an argument of type "Person"
void populateFrom(ListModel r) {
restaurantname.setText(r.getProductName());
ruppees.setText(r.getPrice());
}
}
//=============================================================
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_detais_rest, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
return super.onOptionsItemSelected(item);
}
public void OnPause(){
super.onPause();
}
}
Second activity's code:
package com.firstchoicefood.phpexpertgroup.firstchoicefoodin;
import android.app.ActionBar;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.FragmentManager;
import android.util.Log;
import android.view.Gravity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import com.firstchoicefood.phpexpertgroup.firstchoicefoodin.bean.CARTBean;
import com.firstchoicefood.phpexpertgroup.firstchoicefoodin.bean.ListModel;
import com.firstchoicefood.phpexpertgroup.firstchoicefoodin.database.SqliteController;
public class QuentityActivity extends Activity {
String value=null;
public String TotAmt=null;
String[] cccc;
ImageButton positive,negative;
String position;
static int count = 1;
int tot_amt = 0;
public String countString=null;
String name,price;
String valueid,valueid1,valuename;
public TextView ruppees,submenuname,totalruppees,quantity,addtocart;
SharedPreferences preferences;
SharedPreferences.Editor editor;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_quentity);
ActionBar actionBar = getActionBar();
// Enabling Up / Back navigation
actionBar.setDisplayHomeAsUpEnabled(true);
actionBar.setBackgroundDrawable(new ColorDrawable(Color.parseColor("#ff0000")));
preferences = getSharedPreferences("temp1",1);
editor = preferences.edit();
Intent intent = getIntent();
// get the extra value
value = intent.getStringExtra("quentity");
valuename = intent.getStringExtra("valuename");
valueid = intent.getStringExtra("valueid");
valueid1 = intent.getStringExtra("valueid1");
name=intent.getStringExtra("name");
price=intent.getStringExtra("price");
position=intent.getStringExtra("id");
quantity=(TextView)findViewById(R.id.rastaurantcuisinedetalsrestaurantquantity);
totalruppees=(TextView)findViewById(R.id.rastaurantnamequentitytotal1);
submenuname=(TextView)findViewById(R.id.rastaurantnamesubmenuquentity);
ruppees=(TextView)findViewById(R.id.rastaurantnamequentity1);
positive=(ImageButton)findViewById(R.id.imageButtonpositive);
negative=(ImageButton)findViewById(R.id.imageButtonnegative);
addtocart=(TextView)findViewById(R.id.textViewaddtocart);
buttonclick();
addtocart();
submenuname.setText(name);
ruppees.setText(price);
totalruppees.setText(price);
// new DownloadJSON().execute();
}
public void buttonclick(){
positive.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String totalAmtString = ruppees.getText().toString();
int totAmount = Integer.parseInt(totalAmtString);
//count = Integer.parseInt(getString);
count++;
editor.putInt("COUNTSTRING1", count);
editor.commit();
editor.clear();
Log.i("sunder sharma",""+count);
countString= String.valueOf(count);
tot_amt = totAmount * count;
TotAmt = String.valueOf(tot_amt);
totalruppees.setText(TotAmt);
quantity.setText(countString);
}
});
negative.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String totalAmtString = ruppees.getText().toString();
int totAmount = Integer.parseInt(totalAmtString);
if (count > 1)
count--;
editor.putInt("COUNTSTRING1", count);
editor.commit();
countString = String.valueOf(count);
tot_amt = totAmount * count;
TotAmt = String.valueOf(tot_amt);
totalruppees.setText(TotAmt);
quantity.setText(countString);
}
});
}
public void addtocart(){
addtocart.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
/* Log.i("valueid",valueid);
Log.i("valuename",valuename);
Log.i("valueid1",valueid1);
Log.i("name",name);
Log.i("price",price);
Log.i("id1",position);
SqliteController db = new SqliteController(QuentityActivity.this);
db.insertStudent(new CARTBean(position,name,price,countString,TotAmt));
*/
Intent intent=new Intent();
intent.putExtra("MESSAGE",TotAmt);
intent.putExtra("POSITION",position);
intent.putExtra("COUNTSTRING",countString);
intent.putExtra("VALUENAME",valuename);
intent.putExtra("name",name);
setResult(2,intent);
finish();//finishing activity
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_quentity, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
Collect the data from second activity and put into below intent .Then you will receive first activity.
Intent myIntent = new Intent(secondActivity.this, firstActivity.class);
myIntent.putExtra("COUNTSTRING", CountString); //add data
startActivity(myIntent);
I have action button in my fragment, i follow some tutorial in internet and i have managed to show my action button in my fragment. but for unknown reason when i tap the action button nothing happened.
This is my xml menu
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:yourapp="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent">
<item android:id="#+id/send_card"
android:icon="#drawable/btn_add"
android:title="send card"
yourapp:showAsAction="always"
/>
</menu>
package com.dycode.durexlovers.fragment;
import android.app.AlertDialog;
import android.app.Fragment;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.HorizontalScrollView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import com.androidquery.AQuery;
import com.dycode.durexlovers.R;
import com.dycode.durexlovers.adapter.HorizontalListViewCardAdapter;
import com.dycode.durexlovers.adapter.MomentAdapter;
import com.dycode.durexlovers.adapter.SpiceItUpAdapter;
import com.dycode.durexlovers.adapter.ViewPagerAdapter;
import com.dycode.durexlovers.api.CardApi;
import com.dycode.durexlovers.api.MomentApi;
import com.dycode.durexlovers.card.PreviewCard;
import com.dycode.durexlovers.card.SendCard;
import com.dycode.durexlovers.dao.CardDao;
import com.dycode.durexlovers.dao.MomentDao;
import com.dycode.durexlovers.utils.Constant;
import com.dycode.durexlovers.utils.SessionManager;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import it.sephiroth.android.library.widget.AdapterView;
import it.sephiroth.android.library.widget.HListView;
/**
* Created by Minecraft on 06/01/2015.
*/
public class SpiceItUpFragment extends Fragment {
LinearLayout stripRomantic, stripRomanticAct, stripTease, stripTeaseAct, stripIntimate, stripIntimateAct;
Button btnRomantic, btnTease, btnIntimate, btnNext, btnBack, btnSendCard;
HListView hListView;
private CardApi cardApi;
private List<CardDao> listCard = new ArrayList<CardDao>();
HorizontalListViewCardAdapter adapter;
ProgressDialog dialog;
SessionManager sessionManager;
String email;
TextView tvNameCard, tvDescCard;
ImageView ivCard;
AQuery aQuery;
int pos;
String categoryCard;
public SpiceItUpFragment() {
}
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_spice_it_up, container, false);
stripRomantic = (LinearLayout) rootView.findViewById(R.id.strip_tab_romantic);
stripRomanticAct = (LinearLayout) rootView.findViewById(R.id.strip_tab_romantic_active);
stripTease = (LinearLayout) rootView.findViewById(R.id.strip_tab_tease);
stripTeaseAct = (LinearLayout) rootView.findViewById(R.id.strip_tab_tease_active);
stripIntimate = (LinearLayout) rootView.findViewById(R.id.strip_tab_intimate);
stripIntimateAct = (LinearLayout) rootView.findViewById(R.id.strip_tab_intimate_active);
btnRomantic = (Button) rootView.findViewById(R.id.btnRomantic);
btnTease = (Button) rootView.findViewById(R.id.btnTease);
btnIntimate = (Button) rootView.findViewById(R.id.btnIntimate);
btnNext = (Button) rootView.findViewById(R.id.btnNext);
btnBack = (Button) rootView.findViewById(R.id.btnBack);
btnSendCard = (Button) rootView.findViewById(R.id.btnSendCard);
hListView = (HListView) rootView.findViewById(R.id.hListView);
tvNameCard = (TextView) rootView.findViewById(R.id.tvNameCard);
tvDescCard = (TextView) rootView.findViewById(R.id.tvDescCard);
ivCard = (ImageView) rootView.findViewById(R.id.ivCard);
aQuery = new AQuery(getActivity());
cardApi = new CardApi(getActivity(), cardListener);
adapter = new HorizontalListViewCardAdapter(getActivity(), listCard);
hListView.setAdapter(adapter);
sessionManager = new SessionManager(getActivity());
// get user data from session
HashMap<String, String> user = sessionManager.getUserDetails();
email = user.get(sessionManager.KEY_EMAIL);
categoryCard = "romantic";
cardApi.callApiCard(email, categoryCard);
//hListView.setAdapter( new ArrayAdapter<String>( getActivity(), R.layout.card_horizontal_list_item, activities ) );
btnRomantic.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(!categoryCard.equalsIgnoreCase("romantic")){
categoryCard = "romantic";
stripRomantic.setVisibility(View.INVISIBLE);
stripRomanticAct.setVisibility(View.VISIBLE);
stripTease.setVisibility(View.VISIBLE);
stripTeaseAct.setVisibility(View.INVISIBLE);
stripIntimate.setVisibility(View.VISIBLE);
stripIntimateAct.setVisibility(View.INVISIBLE);
cardApi.callApiCard(email, categoryCard);
}
}
});
btnTease.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(!categoryCard.equalsIgnoreCase("tease")){
categoryCard = "tease";
stripTease.setVisibility(View.INVISIBLE);
stripTeaseAct.setVisibility(View.VISIBLE);
stripRomantic.setVisibility(View.VISIBLE);
stripRomanticAct.setVisibility(View.INVISIBLE);
stripIntimate.setVisibility(View.VISIBLE);
stripIntimateAct.setVisibility(View.INVISIBLE);
cardApi.callApiCard(email,categoryCard);
}
}
});
btnIntimate.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(!categoryCard.equalsIgnoreCase("intimate")){
categoryCard = "intimate";
stripIntimate.setVisibility(View.INVISIBLE);
stripIntimateAct.setVisibility(View.VISIBLE);
stripTease.setVisibility(View.VISIBLE);
stripTeaseAct.setVisibility(View.INVISIBLE);
stripRomantic.setVisibility(View.VISIBLE);
stripRomanticAct.setVisibility(View.INVISIBLE);
cardApi.callApiCard(email,categoryCard);
}
}
});
hListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {
pos = position;
tvNameCard.setText(listCard.get(position).getNameCard());
tvDescCard.setText(listCard.get(position).getDescriptionCard());
String urlCard = Constant.URLImage.CARD + listCard.get(position).getImageCard();
aQuery.id(ivCard).image(urlCard);
}
});
btnNext.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (pos < listCard.size()-1) {
pos = pos + 1;
tvNameCard.setText(listCard.get(pos).getNameCard());
tvDescCard.setText(listCard.get(pos).getDescriptionCard());
String urlCard = Constant.URLImage.CARD + listCard.get(pos).getImageCard();
aQuery.id(ivCard).image(urlCard);
}
}
});
btnBack.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (pos > 0) {
pos = pos - 1;
tvNameCard.setText(listCard.get(pos).getNameCard());
tvDescCard.setText(listCard.get(pos).getDescriptionCard());
String urlCard = Constant.URLImage.CARD + listCard.get(pos).getImageCard();
aQuery.id(ivCard).image(urlCard);
}
}
});
btnSendCard.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(getActivity(), PreviewCard.class);
i.putExtra("id",listCard.get(pos).getIdCard());
i.putExtra("name",listCard.get(pos).getNameCard());
i.putExtra("desc",listCard.get(pos).getDescriptionCard());
String urlCard = Constant.URLImage.CARD + listCard.get(pos).getImageCard();
i.putExtra("url",urlCard);
startActivity(i);
}
});
setHasOptionsMenu(true);
return rootView;
}
CardApi.ApiResultListener cardListener = new CardApi.ApiResultListener() {
#Override
public void onApiResultOk(List<CardDao> listData) {
if (dialog != null)
dialog.dismiss();
listCard.clear();
listCard.addAll(listData);
adapter.notifyDataSetChanged();
pos = listCard.size() / 2;
tvNameCard.setText(listCard.get(pos).getNameCard());
tvDescCard.setText(listCard.get(pos).getDescriptionCard());
String urlCard = Constant.URLImage.CARD + listCard.get(pos).getImageCard();
aQuery.id(ivCard).image(urlCard);
}
#Override
public void onApiPreCall() {
dialog = ProgressDialog.show(getActivity(), "", "loading...");
}
#Override
public void onApiResultError(String errorMessage) {
showDialogNotification(errorMessage);
if (dialog != null)
dialog.dismiss();
}
};
private void showDialogNotification(String message) {
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(
getActivity());
alertDialogBuilder.setTitle("Notification");
alertDialogBuilder.setMessage(message).setCancelable(false)
.setNeutralButton("Ok", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
}
});
AlertDialog alertDialog = alertDialogBuilder.create();
alertDialog.show();
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
super.onCreateOptionsMenu(menu, inflater);
inflater.inflate(R.menu.menu_send_card, menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
super.onOptionsItemSelected(item);
// Handle presses on the action bar items
switch (item.getItemId()) {
case R.id.send_card:
Intent i = new Intent(getActivity(), PreviewCard.class);
i.putExtra("id",listCard.get(pos).getIdCard());
i.putExtra("name",listCard.get(pos).getNameCard());
i.putExtra("desc",listCard.get(pos).getDescriptionCard());
String urlCard = Constant.URLImage.CARD + listCard.get(pos).getImageCard();
i.putExtra("url",urlCard);
startActivity(i);
return true;
default:
return super.onOptionsItemSelected(item);
}
}
}
Thank for your help
change your method like below.you need to call super.onCreateOptionsMenu like below
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
super.onCreateOptionsMenu(menu, inflater);
inflater.inflate(R.menu.menu_send_card, menu);
}
and set setHasOptionsMenu(true); in your oncreateview befor return v;