DWA
DWA

Reputation: 530

Information in intents not send from one activity to another

Being a newbie to Android, I am working on an Android app that should pass information from one activity to another. The information is retreived in the correct way in the first activity - it is logged to the log cat -, but it is not received in the second activity, as the values passed through the intents return null. That´s where I´m stuck and where any hints or help would be very much appreciated.

The first Java class:

package de.die_web_agenten.www.runinstant;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.ActivityNotFoundException;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ListAdapter;
import android.widget.SimpleCursorAdapter;
import android.widget.Toast;

import de.die_web_agenten.www.runinstant.db.TaskContract;
import de.die_web_agenten.www.runinstant.db.TaskDBHelper;


public class AndroidBarcodeQrExample extends Activity {
    /** Called when the activity is first created. */

    static final String ACTION_SCAN = "com.google.zxing.client.android.SCAN";
    private ListAdapter listAdapter;
    private TaskDBHelper helper;


    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_barcode);
    }

    public void scanBar(View v) {
        try {
            Intent intent = new Intent(ACTION_SCAN);
            intent.putExtra("SCAN_MODE", "PRODUCT_MODE");
            startActivityForResult(intent, 0);
        } catch (ActivityNotFoundException anfe) {
            showDialog(AndroidBarcodeQrExample.this, "No Scanner Found", "Download a scanner code activity?", "Yes", "No").show();
        }
    }

    public void scanQR(View v) {
        try {
            Intent intent = new Intent(ACTION_SCAN);
            intent.putExtra("SCAN_MODE", "QR_CODE_MODE");
            startActivityForResult(intent, 0);
        } catch (ActivityNotFoundException anfe) {
            showDialog(AndroidBarcodeQrExample.this, "No Scanner Found", "Download a scanner code activity?", "Yes", "No").show();
        }
    }

    private static AlertDialog showDialog(final Activity act, CharSequence title, CharSequence message, CharSequence buttonYes, CharSequence buttonNo) {
        AlertDialog.Builder downloadDialog = new AlertDialog.Builder(act);
        downloadDialog.setTitle(title);
        downloadDialog.setMessage(message);
        downloadDialog.setPositiveButton(buttonYes, new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialogInterface, int i) {
                Uri uri = Uri.parse("market://search?q=pname:" + "com.google.zxing.client.android");
                Intent intent = new Intent(Intent.ACTION_VIEW, uri);
                try {
                    act.startActivity(intent);
                } catch (ActivityNotFoundException anfe) {

                }
            }
        });
        downloadDialog.setNegativeButton(buttonNo, new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialogInterface, int i) {
            }
        });
        return downloadDialog.show();
    }

    private void updateUI() {
        helper = new TaskDBHelper(AndroidBarcodeQrExample.this);
        SQLiteDatabase sqlDB = helper.getReadableDatabase();
        Cursor cursor = sqlDB.query(TaskContract.TABLE,
                new String[]{ TaskContract.Columns.SCAN_RESULT, TaskContract.Columns.SCAN_FORMAT,TaskContract.Columns._id,
                         TaskContract.Columns.DATE},
                null, null, null, null, null
        );


        listAdapter = new SimpleCursorAdapter(
                this,
                R.layout.task_view,
                cursor,
                new String[]{TaskContract.Columns.SCAN_FORMAT, TaskContract.Columns.SCAN_RESULT, TaskContract.Columns._id},
                new int[]{R.id.taskTextView},
                0
        );

        this.setListAdapter(listAdapter);

    }

    public void onActivityResult(int requestCode, int resultCode, Intent intent) {
        if (requestCode == 0) {
            if (resultCode == RESULT_OK) {
                String contents = intent.getStringExtra("SCAN_RESULT");
                String format = intent.getStringExtra("SCAN_RESULT_FORMAT");
                Toast toast = Toast.makeText(this, "Content:" + contents + " Format:" + format, Toast.LENGTH_LONG);
                toast.show();
                /*Intent SecondIntent = new Intent(AndroidBarcodeQrExample.this, SecondListActivity.class);
                SecondIntent.putExtra("SCAN_RESULT", contents);
                startActivity(SecondIntent);*/
                Intent SecondIntent = new Intent(getBaseContext(), SecondListActivity.class);
                intent.putExtra("SCAN_RESULT", contents);
                intent.putExtra("SCAN_RESULT_FORMAT", format);
                startActivity(SecondIntent);
                Log.d("ADebugTag", "Value: " + (contents));
                Log.d("BDebugTag", "Value: " + (format));
                //updateUI();

            //Context context = getApplicationContext();
            //CharSequence text = "Informationen erfolgreich gespeichert!";
            //int duration = Toast.LENGTH_SHORT;
            //Toast toast = Toast.makeText(context, text, duration);
            }

        }

    }

    public void setListAdapter(ListAdapter listAdapter) {
        this.listAdapter = listAdapter;
    }

}

This is the second activity, where the information is not retreived in the correct way:

package de.die_web_agenten.www.runinstant;


import android.app.ListActivity;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.widget.ListAdapter;
import android.widget.SimpleCursorAdapter;

import java.util.ArrayList;

import de.die_web_agenten.www.runinstant.db.TaskContract;
import de.die_web_agenten.www.runinstant.db.TaskDBHelper;

public class SecondListActivity extends ListActivity {

    // declare class variables
    private ArrayList<Item> m_parts = new ArrayList<Item>();
    private Runnable viewParts;
    private ItemAdapter m_adapter;
    private ListAdapter listAdapter;
    private TaskDBHelper helper;

    /** Called when the activity is first created. */
    public void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        // instantiate our ItemAdapter class
        m_adapter = new ItemAdapter(this, R.layout.list_item, m_parts);
        setListAdapter(m_adapter);

        // here we are defining our runnable thread.
        viewParts = new Runnable(){
            public void run(){
                handler.sendEmptyMessage(0);
            }
        };

        // here we call the thread we just defined - it is sent to the handler below.
        Thread thread =  new Thread(null, viewParts, "MagentoBackground");
        thread.start();
    }

    private void updateUI() {
        helper = new TaskDBHelper(SecondListActivity.this);
        SQLiteDatabase sqlDB = helper.getReadableDatabase();
        Cursor cursor = sqlDB.query(TaskContract.TABLE,
                new String[]{TaskContract.Columns.SCAN_RESULT, TaskContract.Columns.SCAN_FORMAT,
                        TaskContract.Columns.DATE, TaskContract.Columns._id },
                null, null, null, null, null
        );


        listAdapter = new SimpleCursorAdapter(
                this,
                R.layout.task_view,
                cursor,
                new String[]{TaskContract.Columns.SCAN_FORMAT, TaskContract.Columns.SCAN_RESULT, TaskContract.Columns._id},
                new int[]{R.id.taskTextView},
                0
        );

        this.setListAdapter(listAdapter);

    }

    private Handler handler = new Handler()
    {
        public void handleMessage(Message msg)
        {
            // create some objects
            // here is where you could also request data from a server
            // and then create objects from that data.
            /*String sql = String.format("DELETE FROM %s WHERE %s = '%s'",
                    TaskContract.TABLE,
                    TaskContract.Columns.SCAN_FORMAT,
                    TaskContract.Columns.SCAN_RESULT
            );

            helper = new TaskDBHelper(SecondListActivity.this);
            SQLiteDatabase sqlDB = helper.getWritableDatabase();
            sqlDB.execSQL(sql);*/

            Intent SecondIntent = getIntent();
            String contents = SecondIntent.getStringExtra("SCAN_RESULT");
            //String contents = SecondIntent.getStringExtra("SCAN_RESULT", contents);
            String format = SecondIntent.getStringExtra("SCAN_RESULT_FORMAT");

            m_parts.add(new Item(contents, format, 0));

            m_parts.add(new Item("MyItemName #2", "This is item #2", 0));
            Log.d("CDebugTag", "Value: " + (contents));
            //Log.d("DDebugTag", "Value: " + (format));
            /*m_parts.add(new Item("MyItemName", "This is item #3", 0));
            m_parts.add(new Item("MyItemName #2", "This is item #4", 0));
            m_parts.add(new Item("MyItemName", "This is item #5", 0));
            m_parts.add(new Item("MyItemName #2", "This is item #6", 0));
            m_parts.add(new Item("MyItemName", "This is item #7", 0));
            m_parts.add(new Item("MyItemName #2", "This is item #8", 0));
            m_parts.add(new Item("MyItemName", "This is item #9", 0));
            m_parts.add(new Item("MyItemName #2", "This is item #10", 0));*/


            m_adapter = new ItemAdapter(SecondListActivity.this, R.layout.list_item, m_parts);

            // display the list.
            setListAdapter(m_adapter);
            //updateUI();
        }
    };
}

Both activities are registered in the Android manifest for the app:

<activity
    android:name=".MapsActivity"
    android:label="@string/title_activity_maps" />
<activity
    android:name=".ResultsActivity"
    android:label="@string/title_activity_results"
    android:theme="@style/AppTheme.NoActionBar" />
<activity
    android:name=".TrainingActivity"
    android:label="@string/title_activity_training"
    android:theme="@style/AppTheme.NoActionBar" />
<activity
    android:name=".SecondListActivity"
    android:label="@string/title_activity_list"
    android:theme="@style/AppTheme.NoActionBar" />
<activity
    android:name=".AndroidBarcodeQrExample"
    android:label="@string/title_barcode_class"
    android:theme="@style/AppTheme.NoActionBar" />

I am stuck here, as I don´t understand why the information are not retreived through the intent in the second activity, as Android should send the intent and I don´t get any errors in the log cat. Any hints or informations are very welcome, thanks.

Upvotes: 0

Views: 61

Answers (1)

Cynapsis
Cynapsis

Reputation: 118

Your handler object needs a Callback parameter

Handler handler = new Handler(new Handler.Callback() {
    @Override
    public boolean handleMessage(Message message) {
        smth();
        ...
        return messageHandled;
    }
});

You can do this either by using the Handler.Callback interface or implementing your own subclass which is harder than the first option so I recommend using the above implementation. I've tried, it does work this way.

Edit 1 : returning whether the message was handled or not makes sure it is not handled more than once by the handler.

Upvotes: 2

Related Questions