仅意图在一个活动中给出错误的意图中获取数据
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了仅意图在一个活动中给出错误的意图中获取数据相关的知识,希望对你有一定的参考价值。
我正在尝试从适配器中传递意图并将其加入我的活动中。
当我每次这样做时,它都会处于else状态。
它没有得到值,我也不是为什么。当我在任何其他活动中尝试相同的代码时,它工作得很好,但是在此活动中,它总是给出null意图价值。
我知道如何获得和传递意图的答案很多,但就我而言,它在一项活动中不起作用,我也不知道为什么。
我的适配器类:
holder.getSurvey.setOnClickListener(new View.OnClickListener()
@Override
public void onClick(View v)
Intent intent = new Intent(context,AuthorMainScreen.class);
intent.putExtra("work", "getting");
context.startActivity(intent);
我的AuthorMainScreen活动:
public class AuthorMainScreen extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener
Button newSurveyBtn, surveyWithRef, surveyResult;
ArrayList<JSONObject> jsonObjects = new ArrayList<JSONObject>();
public static TextView textView;
DatabaseReference databaseReference, surveyReference;
String referenceNo, loggedInUserId;
AlertDialog dialog;
ProgressDialog progressDialog;
DrawerLayout drawerLayout;
NavigationView navigationView;
LinearLayout linearLayout;
FirebaseAuth firebaseAuth;
TextView headerEmailView, rateOk;
Button headerLogout;
EditText reference;
@Override
protected void onCreate(Bundle savedInstanceState)
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_author_navigation);
progressDialog = new ProgressDialog(this);
progressDialog.setMessage("Processing your request...");
viewDeclaration();
clickFunctionalities();
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawerLayout, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawerLayout.setDrawerListener(toggle);
toggle.syncState();
// drawerLayout.addDrawerListener(actionBarDrawerToggle);
navigationView.setNavigationItemSelectedListener(this);
private void clickFunctionalities()
newSurveyBtn.setOnClickListener(new View.OnClickListener()
@Override
public void onClick(View view)
surveyTitleDialog();
);
surveyWithRef.setOnClickListener(new View.OnClickListener()
@Override
public void onClick(View v)
referenceDialog();
rateOk.setOnClickListener(new View.OnClickListener()
@Override
public void onClick(View view)
referenceNo = reference.getText().toString().trim();
if (!referenceNo.isEmpty())
progressDialog.show();
getSurvey();
dialog.dismiss();
else
progressDialog.dismiss();
reference.setError("Reference # is required");
);
);
surveyResult.setOnClickListener(new View.OnClickListener()
@Override
public void onClick(View view)
referenceDialog();
rateOk.setOnClickListener(new View.OnClickListener()
@Override
public void onClick(View view)
referenceNo = reference.getText().toString().trim();
if (!referenceNo.isEmpty())
progressDialog.show();
getSurveyResultFile();
dialog.dismiss();
else
progressDialog.dismiss();
reference.setError("Reference # is required");
);
);
linearLayout.setOnClickListener(new View.OnClickListener()
@Override
public void onClick(View v)
if (drawerLayout.isDrawerOpen(GravityCompat.START))
drawerLayout.closeDrawer(GravityCompat.START);
else
drawerLayout.openDrawer(GravityCompat.START);
);
headerLogout.setOnClickListener(new View.OnClickListener()
@Override
public void onClick(View v)
FirebaseAuth.getInstance().signOut();
Intent intent = new Intent(AuthorMainScreen.this, LoginSignupActivity.class);
startActivity(intent);
finish();
);
private void surveyTitleDialog()
final AlertDialog.Builder textBuilder = new AlertDialog.Builder(this);
LayoutInflater inflater = this.getLayoutInflater();
View view = inflater.inflate(R.layout.survey_name_dialog, null);
final EditText surveyName = view.findViewById(R.id.edt_set_survey_name);
TextView ok = view.findViewById(R.id.survey_name_btn);
ok.setOnClickListener(new View.OnClickListener()
@Override
public void onClick(View view)
String surveyTitleName = surveyName.getText().toString().trim();
if (!surveyTitleName.equals(""))
dialog.dismiss();
Intent intent = new Intent(AuthorMainScreen.this, MakeSurvey.class);
intent.putExtra("surveyname", surveyTitleName);
Toast.makeText(AuthorMainScreen.this, surveyTitleName, Toast.LENGTH_SHORT).show();
startActivity(intent);
else
surveyName.setError("Title is Required");
);
TextView cancelBtn = view.findViewById(R.id.dismiss_dialog);
cancelBtn.setOnClickListener(new View.OnClickListener()
@Override
public void onClick(View view)
dialog.dismiss();
);
textBuilder.setView(view);
dialog = textBuilder.create();
dialog.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);
dialog.show();
Window window = dialog.getWindow();
window.setLayout(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
dialog.setCancelable(false);
private void getSurvey()
surveyReference = FirebaseDatabase.getInstance().getReference().child(Constants.content).child(Constants.survey).child(referenceNo);
surveyReference.addValueEventListener(new ValueEventListener()
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot)
System.out.println(dataSnapshot);
if (dataSnapshot.hasChildren())
progressDialog.dismiss();
Intent intent = new Intent(getApplicationContext(), GetSurveys.class);
intent.putExtra(Constants.ref_no, referenceNo);
startActivity(intent);
else
progressDialog.dismiss();
Toast.makeText(getApplicationContext(), "Reference number is not valid !!!", Toast.LENGTH_LONG).show();
@Override
public void onCancelled(@NonNull DatabaseError databaseError)
progressDialog.dismiss();
Toast.makeText(getApplicationContext(), "Something went wrong!!!", Toast.LENGTH_SHORT).show();
);
public void getSurveyResultFile()
databaseReference = FirebaseDatabase.getInstance().getReference().child(Constants.content).child(Constants.Answers).child(loggedInUserId).child(referenceNo);
databaseReference.addValueEventListener(new ValueEventListener()
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot)
if (dataSnapshot.exists())
progressDialog.dismiss();
JSONArray dataSnapshotArray = new JSONArray();
JSONArray dataSnapshotChildrenArray;
JSONObject dataSnapshotChildrenAnswer;
JSONArray dataSnapshotChildrenAnswerValues;
for (DataSnapshot ds : dataSnapshot.getChildren())
System.out.println("sdsd" + ds);
dataSnapshotChildrenArray = new JSONArray();
ArrayList<Object> list = (ArrayList<Object>) ds.getValue();
for (int i = 0; i < list.size(); i++)
HashMap<String, Object> map = (HashMap<String, Object>) list.get(i);
Iterator<Map.Entry<String, Object>> finalIterator = map.entrySet().iterator();
dataSnapshotChildrenAnswer = new JSONObject();
while (finalIterator.hasNext())
Map.Entry<String, Object> entry = finalIterator.next();
Object value = entry.getValue();
String key = entry.getKey();
try
dataSnapshotChildrenAnswer.put(key, value);
if (value instanceof ArrayList)
dataSnapshotChildrenAnswerValues = new JSONArray();
ArrayList<String> answers = (ArrayList<String>) value;
for (int j = 0; j < answers.size(); j++)
dataSnapshotChildrenAnswerValues.put(answers.get(j));
dataSnapshotChildrenAnswer.put(key, dataSnapshotChildrenAnswerValues);
catch (JSONException e)
e.printStackTrace();
dataSnapshotChildrenArray.put(dataSnapshotChildrenAnswer);
dataSnapshotArray.put(dataSnapshotChildrenArray);
System.out.println("jso " + dataSnapshotArray);
try
saveCsv(dataSnapshotArray);
catch (IOException e)
e.printStackTrace();
catch (JSONException e)
e.printStackTrace();
else
Toast.makeText(AuthorMainScreen.this, "Sorry!!user or survey not found.", Toast.LENGTH_LONG).show();
progressDialog.dismiss();
@Override
public void onCancelled(@NonNull DatabaseError databaseError)
);
public void saveCsv(JSONArray outerArray) throws IOException, JSONException
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M)
if (checkSelfPermission(android.Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED)
ActivityCompat.requestPermissions(this, new String[]Manifest.permission.WRITE_EXTERNAL_STORAGE, 1);
String fileName = referenceNo + " Result";
String rootPath = Environment.getExternalStorageDirectory().getAbsolutePath() + "/test/";
File dir = new File(rootPath);
if (!dir.exists())
dir.mkdir();
File file = null;
file = new File(rootPath, fileName);
if (!file.exists())
progressDialog.dismiss();
file.createNewFile();
if (file.exists())
progressDialog.dismiss();
CSVWriter writer = new CSVWriter(new FileWriter(file), ',');
for (int i = 0; i < outerArray.length(); i++)
JSONArray innerJsonArray = (JSONArray) outerArray.getJSONArray(i);
for (int k = 0; k < innerJsonArray.length(); k++)
String[][] arrayOfArrays = new String[innerJsonArray.length()][];
JSONObject innerJsonObject = (JSONObject) innerJsonArray.getJSONObject(k);
String[] stringArray1 = new String[innerJsonObject.length()];
// stringArray1[0]= (String) innerJsonObject.getString("type");
stringArray1[1] = "Questions";
stringArray1[2] = "Answers";
stringArray1[1] = (String) innerJsonObject.getString("title");
stringArray1[2] = "";
JSONArray jsonArray = (JSONArray) innerJsonObject.getJSONArray("answer");
for (int j = 0; j < jsonArray.length(); j++)
stringArray1[2] += jsonArray.get(j).toString();
stringArray1[2] += ",";
arrayOfArrays[k] = stringArray1;
writer.writeNext(arrayOfArrays[k]);
System.out.println("aa " + Arrays.toString(arrayOfArrays[k]));
writer.close();
Toast.makeText(this, fileName + " is been saved at " + rootPath, Toast.LENGTH_LONG).show();
public void referenceDialog()
final AlertDialog.Builder rateBuilder = new AlertDialog.Builder(this);
LayoutInflater inflater = this.getLayoutInflater();
View view = inflater.inflate(R.layout.survey_refno_dialog, null);
reference = view.findViewById(R.id.edt_survey_ref_no);
rateOk = view.findViewById(R.id.ref_btnOk);
TextView rateCancel = view.findViewById(R.id.ref_btnCancel);
rateBuilder.setView(view);
rateCancel.setOnClickListener(new View.OnClickListener()
@Override
public void onClick(View view)
dialog.dismiss();
);
dialog = rateBuilder.create();
dialog.show();
Window rateWindow = dialog.getWindow();
rateWindow.setLayout(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
dialog.setCancelable(false);
private void viewDeclaration()
newSurveyBtn = findViewById(R.id.new_surveys_button);
surveyWithRef = findViewById(R.id.get_survey_button);
surveyResult = findViewById(R.id.analyze_survey);
linearLayout = findViewById(R.id.hamburg_icon_layout);
drawerLayout = findViewById(R.id.drawer_layout);
navigationView = findViewById(R.id.navigation_view);
View view = navigationView.getHeaderView(0);
headerEmailView = view.findViewById(R.id.header_email);
headerLogout = findViewById(R.id.nav_logout);
firebaseAuth = FirebaseAuth.getInstance();
if (firebaseAuth.getCurrentUser() != null)
String userEmail = firebaseAuth.getCurrentUser().getEmail();
headerEmailView.setText(userEmail);
if (firebaseAuth.getCurrentUser() != null && firebaseAuth.getCurrentUser().getUid() != null)
loggedInUserId = firebaseAuth.getCurrentUser().getUid();
@Override
public boolean onNavigationItemSelected(@NonNull MenuItem menuItem)
switch (menuItem.getItemId())
case R.id.menu_share:
Intent intent = new Intent(Intent.ACTION_SEND);
intent.setType("text/plain");
intent.putExtra(Intent.EXTRA_SUBJECT, "DataPro");
intent.putExtra(Intent.EXTRA_TEXT, Constants.shareMessage);
startActivity(Intent.createChooser(intent, "Share Via"));
drawerLayout.closeDrawer(GravityCompat.START);
break;
case R.id.menu_survey_count:
startActivity(new Intent(getApplicationContext(), UserAllSurveys.class));
drawerLayout.closeDrawer(GravityCompat.START);
break;
case R.id.menu_new_instruments:
startActivity(new Intent(getApplicationContext(), CreateInstrument.class));
drawerLayout.closeDrawer(GravityCompat.START);
break;
case R.id.menu_about_us:
Toast.makeText(getApplicationContext(), "About us", Toast.LENGTH_SHORT).show();
drawerLayout.closeDrawer(GravityCompat.START);
break;
return true;
@Override
protected void onStart()
super.onStart();
Intent intent = getIntent();
/*if (intent.hasExtra("work") )
String k = getIntent().getStringExtra("work");
Toast.makeText(this, k, Toast.LENGTH_SHORT).show();
else
Toast.makeText(this, "eroor" , Toast.LENGTH_SHORT).show();
*/
Bundle bundle = getIntent().getExtras();
if (bundle != null )
String k = bundle.getString("work");
Toast.makeText(this, k, Toast.LENGTH_SHORT).show();
else
Toast.makeText(this, "error" , Toast.LENGTH_SHORT).show();
@Override
public void onBackPressed()
super.onBackPressed();
答案
尝试这样
Bundle bundle = getIntent().getExtras();
if (bundle != null )
String k = bundle.getString("work");
Toast.makeText(this, k, Toast.LENGTH_SHORT).show();
else
Toast.makeText(this, "error" , Toast.LENGTH_SHORT).show();
另一答案
您是否有另一个具有相同类名但包名称不同的类?因为您的接收方活动(AuthorMainScreen)中似乎没有多余的参数。有时这样的错误比其他逻辑错误要花更多的时间。或者您也可以通过注释其余代码来尝试在onCreate()上调用它。
以上是关于仅意图在一个活动中给出错误的意图中获取数据的主要内容,如果未能解决你的问题,请参考以下文章